Serve image with PHP script vs direct loading an image

Sending images through a script is nice for other things like resizing and caching on demand.

As answered by Pascal MARTIN the function readfile and these headers are the requirements:

  • Content-Type
    • The mime type of this content
    • Example: header('Content-Type: image/gif');
    • See the function mime_content_type
    • Types
      • image/gif
      • image/jpeg
      • image/png

But beside the obvious content-type you should also look at other headers such as:

  • Content-Length
    • The length of the response body in octets (8-bit bytes)
    • Example: header('Content-Length: 348');
    • See the function filesize
    • Allows the connectio to be better used.
  • Last-Modified
    • The last modified date for the requested object, in RFC 2822 format
    • Example: header('Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT');
    • See the function filemtime and date to format it into the required RFC 2822 format
      • Example: header('Last-Modified: '.date(DATE_RFC2822, filemtime($filename)));
    • You can exit the script after sending a 304 if the file modified time is the same.
  • status code
    • Example: header("HTTP/1.1 304 Not Modified");
    • you can exit now and not send the image one more time

For last modified time, look for this in $_SERVER

  • If-Modified-Since
    • Allows a 304 Not Modified to be returned if content is unchanged
    • Example: If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
    • Is in $_SERVER with the key http_if_modified_since

List of HTTP header responses

Leave a Comment