【PHP】画像のキャッシュを有効にする方法

PHPから画像を送信する場合にキャッシュを有効にする方法


$file_name = "【画像のパス】";
// 存在チェック
if (! file_exists($url)) {
    exit;
}

// 読込許可をチェック
if (! is_readable($url)) {
    exit;
}

$file_name = explode("/",$url);
$file_name = end($file_name);

//$type_id   = exif_imagetype($file_name);
//$type_name = image_type_to_mime_type($type_id);

$last_modified = filectime($file_name); //最終更新日を作成(キャッシュ用)

$path_parts = pathinfo($file_name); // ファイル情報
$file_ext = strtolower($path_parts['extension']); // 拡張子を小文字置換

// 拡張子によるContent-TypeとContent-Dispositionの設定
if ($file_ext == 'pdf') {
    $content_type = 'application/pdf';
} elseif ($file_ext == 'gif') {
    $content_type = 'image/gif';
} elseif ($file_ext == 'jpg' || $file_ext == 'jpeg') {
    $content_type = 'image/jpeg';
} elseif ($file_ext == 'png') {
    $content_type = 'image/png';
} else {
    $content_type = 'application/octet-stream';
}

// ロードするファイル名が未定義の場合は元ファイル名と同じに
if (empty($load_name)) {
    $load_name = $path_parts['filename'];
}

if (preg_match('/^(gif|jpe?g|png)$/', $file_ext)) {
        $content_disposition = 'inline'; // inline ブラウザに表示
    } else {
        $content_disposition = 'attachment'; // attachment ダウンロード
}

///もしキャッシュ更新確認リクエストなら
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;
    }
}

//nocache—- ブラウザにキャッシュしないで(デフォルト)
//private—- ブラウザにキャッシュして
//session_cache_limiter('public'); //ブラウザとキャッシュサーバ(プロクシとか)にキャッシュして
header("Last-Modified: " . date('r', $last_modified));
header("Content-type: " . $content_type);
header('Content-Disposition: ' . $content_disposition . '; filename=' . $load_name);
header('Pragma: cache');
header("Cache-Control: max-age=".(60*60*24*100)); // 100日キャッシュしていい
//header('Content-Type: ' . $content_type);
//echo file_get_contents($file_name);
readfile($file_name); //20MB以下

画像の容量 20MB以上の参考