MxLDevs
MxLDevs

Reputation: 19506

Serve the contents of text files in a webpage

I have a PHP script that takes parameters and prints data onto the screen from a text file stored somewhere on the internet..

For example, you might request

http://example.com/resource.php?id=5

Say that request is an attempt to access a text file resource, so I go ahead and find the URL to the text file, read it, and then display it on the page:

$f = fopen($url, "rb");
echo stream_get_contents($f);

However the formatting isn't correct; it's missing new-lines. I tried using r mode, but the output was still the same.

Then I remembered that new-lines in text files (\n, \r\n, possibly others) aren't treated as line breaks in HTML, so I went and replaced all occurrences of \r\n and \n to <br>

And now the new lines appear properly. However, I noticed there were large patches of empty space here and there, and realized it was because those particular text looked like <this> and <that>

At this point I realize this doesn't seem like a good idea, especially since browsers know how to render text files anyways. I could simply re-direct them to the URL of the text file I guess, but I am planning to provide functionality that will query multiple files for input, so a redirect might not work too well.

How do I serve contents from a text file reliably?

Upvotes: 2

Views: 56

Answers (1)

Quentin
Quentin

Reputation: 943563

If you want to tell the browser that you are serving text and not HTML then:

header("Content-Type: text/plain");

Upvotes: 4

Related Questions