开发者

PHP JPEG headers to stop image from downloading

开发者 https://www.devze.com 2022-12-14 17:28 出处:网络
I am currently using the script below to output the contents of a JPEG straight from a file. The reason I\'m doing so is because I\'m using mod_rewrite/php to mask the name of the original file. This

I am currently using the script below to output the contents of a JPEG straight from a file. The reason I'm doing so is because I'm using mod_rewrite/php to mask the name of the original file. This is working partially as expected, except that Safari insists on downloading the photo instead of just allowing me to see it in the browser. Am I missing a header? Also, what modifications could I make to improve performance?

    error_reporting(0);

    // Find which image we're trying to get
    $_GET['id'];

    // In the real script, I do some proccessing here
    $filename = $_GET['id'] . '.jpg';

    // Getting headers sent by the client.
    $headers = apache_request_headers(); 

    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($filename))) {

        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($filename)).' GMT', true, 304);

    } else {

        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($filen开发者_Go百科ame)).' GMT', true, 200);
        header('Content-Length: '.filesize($filename));
        header('Content-Type: image/jpeg');
        print file_get_contents($filename);

    }

?>

Thanks!


I can't say why Safari is treating your images as attachments/downloads. I actually tested it in the latest Safari 4 on SL and it works OK. You could try sniffing the HTTP conversation and make sure no extra headers (e.g. content-disposition) are creeping in. Also it may pay to check over Safari config settings, maybe something subtle is different there to your other browsers?

On the topic of performance:

First I would try to eliminate the PHP altogether. See if you can leverage your webserver's modules/configuration to achieve your goal.

If you can't do without the PHP, then you could try letting the webserver handle the actual delivery. You can do this in nginx with X-Accel-Redirect and in lighttpd and apache with X-Sendfile.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号