0

PHPを介して画像を出力する場合、image_jpegまたはfile_get_contentsjpgファイルへの直接リンクを使用する場合の2倍以上の時間がかかります。
これらのファイルは約180kbです。
サムネイル(4kbの画像)では、リンクとPHP経由の出力の間に時間差はほとんどありません。

ファイルが大きいとPHPの出力が遅くなる理由と、それを修正する方法を知っている人はいますか?

4

2 に答える 2

3

私が考えることができるのは、クライアントに直接送信するのではなく、PHP を介して解析すると 2 回解析されることだけです。file_get_contents はその内容を実行するため、コンテンツを読み取り、クライアントに送信します。私は間違っているかもしれません。

于 2013-03-13T11:20:12.783 に答える
0

image_jpeg と file_get_contents には違いがあります。1 つ目は jpeg を作成する gd 関数で、これには時間がかかります。2 つ目は、ファイルからデータを読み取るだけです。

問題は、それをどのようにブラウザに出力するかです。適切な対策を講じないと、コンテンツがキャッシュされないため、ブラウザーは毎回コンテンツをダウンロードする必要があります。静的画像は常にブラウザーによってキャッシュされ、最初の読み込み後はほとんど時間がかかりません (HEAD リクエストのみ)。

このコードを試してください:

function CachedFileResponse($thefile,$nocache=0) {
  if (!file_exists($thefile)) {
    error_log('cache error: file not found: '.$thefile);
    header('HTTP/1.0 404 Not Found',true,404);
  } else {
    $lastmodified=gmdate('D, d M Y H:i:s \G\M\T', filemtime($thefile));
    $etag = '"'.md5($lastmodified.filesize($thefile).$thefile).'"';
    header('ETag: '.$etag);
    header('Last-Modified: '.$lastmodified);
    header('Cache-Control: max-age=3600');
    header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time()+86400));
    $ext=strtolower(substr($thefile,strrpos($thefile,'.')+1));
    $fname=substr($thefile,strrpos($thefile,'/')+1);
    if ($ext=='jpg' || $ext=='jpeg') {
      header('Content-Type: image/jpeg');
    } elseif ($ext=='gif') {
      header('Content-Type: image/gif');
    } elseif ($ext=='png') {
      header('Content-Type: image/png');
    } else {
      header('Content-Type: application/binary');
    }
    header('Content-Length: ' . filesize($thefile));
    header('Content-Disposition: filename="'.$fname.'"');

    $ifmodifiedsince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false;
    $ifnonematch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;
    if ($nocache || (!$ifmodifiedsince && !$ifnonematch) ||
       ($ifnonematch && $ifnonematch != $etag) ||
       ($ifmodifiedsince && $ifmodifiedsince != $lastmodified)) {
      error_log('cache miss: '.$thefile);
      $fp = fopen($thefile, 'rb');
      fpassthru($fp);
      fclose($fp);
    } else {
      error_log('cache hit: '.$thefile);
      header("HTTP/1.0 304 Not Modified",true,304);
    }
  }
}
于 2013-03-13T11:25:14.767 に答える