Search code examples
phphtmlapacheimage-caching

Image generated with PHP caching


I have a script that is generating an image with PHP on a server, in the form of image.png. I'm then using this image in different places using <img src="http://domain.com/images/image.png" />.

The problem I'm running into is that even though the image is being regenerated every 30 minutes, it seems to be cached and won't show the new values until I go to http://domain.com/images/image.png and then ctrl+shift+refresh.

Is there any way I can keep the image name the same, but make it always show the newest version of the image?


Solution

  • There are a few options, depending on your situation. If "images/image.png" is an actual file on the server and you are accessing it directly, then you have to change the cache settings on the folder or use .htaccess to inform a browser to resend it.

    <FilesMatch "\.(ico¦pdf¦flv¦jpg¦jpeg¦png¦gif¦js¦css¦swf)$">
    ExpiresDefault A604800
    Header set cache-control: "no-cache, public, must-revalidate"
    </FilesMatch> 
    

    If you are using PHP to find the image and returning it, you can use PHP to send headers.

    header("Expires: ".gmdate("D, d M Y H:i:s", time()+1800)." GMT");
    header("Cache-Control: max-age=1800");
    

    To do it perfectly with PHP, you can check if its actually modified

    $last_modified_time = @filemtime($file);
    header("Expires: ".gmdate("D, d M Y H:i:s", $last_modified_time+1800)." GMT"); 
    //change with $last_modified_time instead of time().
    //Else if you request it 29mins after it was first created, you still have to wait 30mins
    //but the image is recreated after 1 min.
    
    header("Cache-Control: max-age=1800");
    header("Vary: Accept-Encoding");
    
    // exit if not modified
    if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
        if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time) { 
            header("HTTP/1.1 304 Not Modified"); 
            return;
        }
    }