LoginSignup
31
34

More than 5 years have passed since last update.

PHPから画像を送信する際にキャッシュを有効にしておく

Posted at

認証が必要な画像を送信する際に、PHPでチェックをした上で、送信するが、
何度もリクエストされると嫌なので、ブラウザのキャッシュを有効にして送る。

PHPは標準機能がキャッシュ無効ヘッダ(pragma :no-cache)を送るので、明示的に上書きしないと効果がでない。

send_image.php
<?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);

31
34
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
34