Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Cache images from PHP output

Sometime you need to generated image using PHP and mostly it's because you want to make dynamical image, that changes often, like CAPTCHAs. But there are rare occasions, when this image do not change. OF course browser usually don't cache PHP generated images, but if image that is outputted by PHP doesn't change, why shouldn't it be cached? As it will optimize your website page load, thus making user experience more pleasant.

Here is a way how you can cache images that are generated by PHP. This function just checks headers to see if image is up to date and sends 304 code if it is, so browser would use cached version and not download new one. Else new image is outputted to browser.

This example shows you the way to cache files already stored on server, but you can easily modify it at displayGraphicFile functions else section to output for example GD generated image
<?php
// return the browser request header 
// use built in apache ftn when PHP built as module, 
// or query $_SERVER when cgi 
function getRequestHeaders() 
{ 
    if (function_exists("apache_request_headers")) 
    { 
        if($headers = apache_request_headers()) 
        { 
            return $headers; 
        } 
    } 

    $headers = array(); 
    // Grab the IF_MODIFIED_SINCE header 
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) 
    { 
        $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE']; 
    } 
    return $headers; 
}

// Return the requested graphic file to the browser 
// or a 304 code to use the cached browser copy 
function displayGraphicFile ($graphicFileName, $fileType='jpeg') 
{ 
    $fileModTime = filemtime($graphicFileName); 
    // Getting headers sent by the client. 
    $headers = getRequestHeaders(); 
    // Checking if the client is validating his cache and if it is current. 
    if (isset($headers['If-Modified-Since']) && 
        (strtotime($headers['If-Modified-Since']) == $fileModTime)) 
    { 
        // Client's cache IS current, so we just respond '304 Not Modified'. 
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
                ' GMT', true, 304); 
    } 
    else 
    { 
        // Image not cached or cache outdated, we respond '200 OK' and output the image. 
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
                ' GMT', true, 200); 
        header('Content-type: image/'.$fileType); 
        header('Content-transfer-encoding: binary'); 
        header('Content-length: '.filesize($graphicFileName)); 
        readfile($graphicFileName); 
    } 
} 

//example usage
displayGraphicFile("./images/image.png");

?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus