Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the browser to cache images, with PHP?

I'm totally new to how to cache images.

I output all images in a gallery with PHP, and want the images already shown, to be cached by the browser, so the PHP script don't have to output the same image again. All I want is the images to show up faster.

When calling an image I do like this:

<img src="showImage.php?id=601"> 

and the showImage.php-file does:

$id = (int) $_GET['id']; $resultat = mysql_query("     SELECT filename, id     FROM Media      WHERE id = $id "); $data = mysql_fetch_assoc($resultat);  ...  //Only if the user are logged in if(isset($_SESSION['user'])){     header("Content-Type: image/jpeg");      //$data['filename'] can be = dsSGKLMsgKkD3325J.jpg     echo(file_get_contents("images/".$data['filename'].""));  } 
like image 285
Johan Avatar asked Sep 06 '09 15:09

Johan


People also ask

How are browsers cached images?

Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache. The browser cache is cross-page so it works for any page loaded into the browser.

Does browser automatically cache images?

Yes the browser will cache them, often even when your headers say otherwise.

Can PHP files be cached?

The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine. Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths.


1 Answers

First of all, if you're using sessions, you must disable session_cache_limiter (by setting it to none or public). Headers it sends are pretty bad for caches.

session_cache_limiter('none'); 

Then send Cache-Control: max-age=number_of_seconds and optionally an equivalent Expires: header.

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

For the best cacheability, send Last-Modified header and reply with status 304 and empty body if the browser sends a matching If-Modified-Since header.

header('Last-Modified: '.gmdate(DATE_RFC1123,filemtime($path_to_image))); 

For brevity I'm cheating here a bit (the example doesn't verify the date), but it's valid as long as you don't mind browsers keeping the cached file forever:

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {    header('HTTP/1.1 304 Not Modified');    die(); } 
like image 196
Kornel Avatar answered Oct 09 '22 17:10

Kornel