Output an Image in PHP

前端 未结 12 1256
萌比男神i
萌比男神i 2020-11-22 14:33

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

12条回答
  •  生来不讨喜
    2020-11-22 14:52

    You can use finfo (PHP 5.3+) to get the right MIME type.

    $filePath = 'YOUR_FILE.XYZ';
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $contentType = finfo_file($finfo, $filePath);
    finfo_close($finfo);
    
    header('Content-Type: ' . $contentType);
    readfile($filePath);
    

    PS: You don't have to specify Content-Length, Apache will do it for you.

提交回复
热议问题