I have a php script that I use to send images to mobile devices on request. In the current version the script runs and before the end I use imagePNG() to output the image to the device but in doing some reading in the examples in the php manual online I saw this example:
<?php
header("Content-Type: image/png");
# Generate cachefile for image, if it doesn't exist
if( !file_exists($cachefile) ) {
$im = generateimage(); # some code generates an image resource
imagepng($im, $cachefile); # store the image to cachefile
# don't output it like this:
/* imagepng($im);*/
imagedestroy($im);
}
$fp = fopen($cachefile, 'rb'); # stream the image directly from the cachefile
fpassthru($fp);
exit;
?>
I used this example with some modifications to send my images to mobile and it works fine but I have some questions Id like to ask:
1) is this more efficient than creating an image from the file and sending using imagePNG?
2) Also shouldnt I close the file right after using fpassthru?
3) If I do use fopen does that mean that the file is locked meaning no other devices but that one would be able to access it for that moment its being streamed?
Any opinions on the matter would be greatly appreciated.
I think that caching the generated image is a good idea if you have a busy site. It will certainly save memory and CPU cycles in exchange for some hard drive space.
In regards to closing the file after using
fpassthru, it is unnecessary as PHP will close the file when the script terminates. Since the very next line callsexit, there is no need to explicitly close the file. If there was more going on after outputting the image, I would recommend closing the file when no longer in use.As for your third question, since you have not called flock, the file is not locked. If one process has it open for reading, another can open it for reading at the same time.
Just a final note, you could use the function readfile to output the file. This saves you having to call
fopen, but internally,readfileandfpassthrucall the same PHP functionphp_stream_passthruso there is little to no difference in time or efficiency based on which one you use.