문제
동일한 디렉토리에 PHP 파일과 이미지가 있습니다. PHP 파일을 어떻게 제목을 JPEG로 설정하고 이미지를 "당기기"하도록하는 방법은 어떻게해야합니까? 그래서 내가 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은 파일에서 데이터를 읽고 출력 버퍼로 직접 씁니다. 파일_get_contents는 먼저 전체 파일을 메모리로 끌어 당긴 다음 출력합니다. 파일이 매우 큰 경우 readfile을 사용하면 큰 차이가 있습니다.
귀엽기를 원한다면 마지막 수정 된 시간을 출력하고 들어오는 HTTP 헤더를 확인할 수 있습니다. 수정 된 경우 헤더, 빈 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 유형을 결정하는 방법을 알아 내야합니다. 이는 매우 사소해야합니다.
제휴하지 않습니다 StackOverflow