質問

同じディレクトリにPHPファイルと画像があります。 PHPファイルを取得して、ヘッダーをjpegおよび" pull"として設定するにはどうすればよいですか?それに画像。したがって、file.phpに移動すると、画像が表示されます。 file.phpをfile_created.jpgに書き換えて動作する必要がある場合。

役に立ちましたか?

解決

別の回答で示唆されているように file_get_contents を使用する代わりに、 readfile を実行し、さらにHTTPヘッダーを出力して適切に再生します。

   <?php
    $filepath= '/home/foobar/bar.gif'
    header('Content-Type: image/gif');
    header('Content-Length: ' . filesize($filepath));
    readfile($file);
   ?>

readfileはファイルからデータを読み取り、出力バッファーに直接書き込みますが、file_get_contentsは最初にファイル全体をメモリにプルしてから出力します。ファイルが非常に大きい場合、readfileを使用すると大きな違いが生じます。

より簡潔にしたい場合は、最終変更時刻を出力し、 If-Modified-Since ヘッダーを返し、空の304応答を返して、ブラウザーに既に現在のバージョンがインストールされていることを伝えます。...それをするかもしれません:

$filepath= '/home/foobar/bar.gif'

$mtime=filemtime($filepath);

$headers = apache_request_headers(); 
if (isset($headers['If-Modified-Since']) && 
    (strtotime($headers['If-Modified-Since']) >= $mtime)) 
{
    // Client's cache IS current, so we just respond '304 Not Modified'.
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
    exit;
}


header('Content-Type:image/gif');
header('Content-Length: '.filesize($filepath));
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');
readfile($filepath);

他のヒント

次のように簡単になります:

<?php
    $filepath= '/home/foobar/bar.jpg';
    header('Content-Type: image/jpeg');
    echo file_get_contents($filepath);
?>

正しいmimeタイプを決定する方法を理解する必要がありますが、これは非常に簡単です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top