tags:

views:

369

answers:

4

If I put this tag in my HTML:

<img src="http://server/imageHandler.php?image=someImage.jpg" />

instead of

<img src="http://server/images/someImage.jpg" />

and use the imageHandler.php script to read the image file, output expire headers and print the image data, i expect it to be slower. Is this a viable way to manipulate image headers or the performance penalty is too much since images are all around. Are there other ways to set expire headers on images through my php code?

+2  A: 

Try something like

header("Expires: <the date>");
http_send_file("someImage.jpg");

from http://us3.php.net/manual/en/function.http-send-file.php The http_send_file function (if it works the way I think it does) copies the file directly from disk to the network interface, so it sends the image itself about as fast as the server would natively. (Of course, the time taken to run the PHP interpreter will still make the overall request a little slower than serving a static file.)

As at least one other answer has mentioned, probably the best way to set an Expires header (or any other header), if you're running Apache, is to use an .htaccess file, or better yet if you have access to the main configuration files of the server, put the Expires configuration there. Have a look at mod_expires.

David Zaslavsky
I suppose that running php instead of letting the server fetch the file adds overhead itself. In your experience, do you think that it can be neglected for larger applications ?
Discodancer
My impression is that it's best to let the server handle as much as possible by itself, without PHP. But in my experience, the performance difference is slight, unless your server is very busy.
David Zaslavsky
A: 

That would depend on what task imageHandler.php performs. YOu can measure it by printing out the time in milliseconds in your code.

Rimian
+1  A: 

If the imagehandler is using GD or Imagick it will be considerably slower than a regular img tag.

I would suggest caching the image output to a temporary file, if the file exists, the imagehandler just outputs that raw data but if a new file should be created, then it is generated once and then used again for the cache.

You can use htaccess to set expiry.

.htaccess Caching

Ólafur Waage
+3  A: 

Yes, running any PHP script is slower than serving a static file.

Instead, you can set expire headers using Apache configuration directives. See the documentation for mod_expires. For example, you can put the following directives in an Apache httpd.conf or .htaccess file:

# enable expirations
ExpiresActive On
# expire JPG images after a month in the client's cache
ExpiresByType image/jpg A2592000
Bill Karwin