Skip to content

Instantly share code, notes, and snippets.

@takuya
Created March 29, 2012 15:01
Show Gist options
  • Save takuya/2238247 to your computer and use it in GitHub Desktop.
Save takuya/2238247 to your computer and use it in GitHub Desktop.
PHPから画像を送信する際にキャッシュを有効にしておく ref: http://qiita.com/items/938139ba8f20a71f8915
<?php
$file_name = some_function();
//画像タイプ判別
$type_id = exif_imagetype($file_name);
$type_name = image_type_to_mime_type($type_id);
//var_dump($type_name);
//最終更新日を作成(キャッシュ用)
$last_modified = filectime($file_name);
///もしキャッシュ更新確認リクエストなら
if(isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])){
$str_time = $_SERVER["HTTP_IF_MODIFIED_SINCE"];
$last_modified_since = strtotime($str_time);
if($last_modified_since == $last_modified){
//ファイル更新がなければ、キャッシュ有効を返す。
header("HTTP/1.1 304 image not modified");
header('Pragma: cache');
header("Cache-Control: max-age=".(60*60*24*100)); // 100日キャッシュしていい
exit;
}
}
//画像を返す。
header("Last-Modified: " . date('r', $last_modified));
header("Content-type: " . $type_name);
//キャッシュを有効にする
header('Pragma: cache');
header("Cache-Control: max-age=".(60*60*24*100)); // 100日キャッシュしていい
echo file_get_contents($file_name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment