views:

163

answers:

1

I am using the PHP readfile function to read a file and print it like so: print readfile ('anyfile'). This works, but the content length of the file is added at the end of the string also. Why?

+2  A: 

readfile prints out the contents itself and returns the content length -- you're effectively printing the contents with readfile and then printing the content length with print. Remove print and just use

readfile('anyfile');
Andy E
Ah, clarifying. Any idea why they made this function output two variables? Not very useful when you don't want to output something straight away.
Derk
@Derk, they didn't. It outputs the file contents and returns the byte length. There's a number of functions like this that write directly to the output buffer and there's usually a similar alternative. One such alternative in this case might be `file_get_contents()`
Andy E
I'm not sure what you mean by "output it straight away", `readfile()` outputs -- writes to the output buffer -- the instant it is called/before it returns.
Andy E
Well you might want to store the contents into a variable first. I'm using `readfile` because it doesn't use as much memory, as I read somewhere.
Derk
@Derk: `file_get_contents()` is what you need for performance and storing the contents into a variable: `file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.`
Andy E
From a [thread](http://bytes.com/topic/php/answers/705790-file_get_contents-vs-readfile) with the same reference you make: "Actually, readfile doesn't read the whole file, it uses mmap if possible, otherwise reads/writes in 8K chunks, thus conserving memory."Someone tried it with a 179MB file and the memory usage was 1.7MB. So, whatever fits the purpose.
Derk
@Derk: Good to know, but that was also my point. If you want the contents in a variable, use `file_get_contents`, if you want to dump the contents without any manipulation use `readfile`.
Andy E