Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Created September 11, 2014 15:36
Show Gist options
  • Save khoand0000/b7848d22b51163942897 to your computer and use it in GitHub Desktop.
Save khoand0000/b7848d22b51163942897 to your computer and use it in GitHub Desktop.
http://phpsnips.com/473/Cache-PHP-Generated-Images#.VBG--vmSySo Stops PHP from sending a fresh version of an image if the browser already has it in its cache.
<?php
header("Cache-Control: private, max-age=10800, pre-check=10800");
header("Pragma: private");
// Set to expire in 2 days
header("Expires: " . date(DATE_RFC822,strtotime(" 2 day")));
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
// if the browser has a cached version of this image, send 304
header('Last-Modified: '.$_SERVER['HTTP_IF_MODIFIED_SINCE'],true,304);
exit;
}
// Generate an image below either using GD or a file reader such as:
// readfile(), fread(), file_get_contents(), etc.
$path = "/path/to/my/image.jpg";
$info = pathinfo($path);
switch($info["extension"]){
case "jpg":
$mime = "image/jpeg";
break;
case "gif":
$mime = "image/gif";
break;
case "png":
$mime = "image/png";
break;
}
header("content-type: $mime");
readfile($path);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment