Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • PHP: How to cache images in browser using php?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 734
    Comment on it

    When there are multiple images loaded on the page, this may cause page to load slower. In order to increase the speed of the page we need to cache the images via .htaccess or php code. Now I am writing down the php code that will store images in cache of the browser. This is how it is done:

    First of all send Cache-Control: max-age=number_of_seconds and optionally equivalent Expires: header.

    session_cache_limiter('none');
    header('Cache-control: max-age='.(60*60*24*365));
    header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*365));

    In order to get best caching experience you need to send Last-Modified header and reply with status 304 and empty body if browser sends If-Modified-Since header

    header('Last-Modified: '.gmdate(DATE_RFC1123,filemtime($path_to_image)));
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
       header('HTTP/1.1 304 Not Modified');
       die();
    }

    All done! Now load the page, images will be stored in the browser cache now, from the next time page will load images from the cache.

    Thanks for reading the blog.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: