faster fopen or file_get_contents?

Rami Dabain picture Rami Dabain · Oct 18, 2011 · Viewed 21.2k times · Source

i am running multiple websites with high traffic , as a requirement , all images are downloaded via image.php?id=IMAGE_ID_HERE . If you ever done that before , you know that that file will be reading the file image and echoing it to the browser with special headers .

My problem is , the load on the server is very high (150-200) and TOP command shows multiple instances of image.php , so image.php is running slow !

the problem probably is fopen loading the image to the memory before sending it to the client. How to read a file and pass it through directly?

Thank you guys


UPDATE

After you optimized the code, used caching wherever possible, do create a CDN . couple of servers, sync methods, load balancers and no need to worry about requests anymore :)

Answer

user652649 picture user652649 · Oct 18, 2011

fopen and file_get_contents are nearly equivalent

to speed up with consistence the page load you can use

http://www.php.net/fpassthru

or, even better

http://www.php.net/readfile

with those functions, content of file is printed directly, byte per byte

as opposed to file_get_contents, for example, where you store the whole data inside a variable

$var = file_get_contents();

so, to make these work correctly you will need to disable output buffering (otherwise it would make readfile() pointless) in the page that serves the images

hope this helps!