Forcing an image download in PHP. Works locally but breaks on live Linux server

前端 未结 3 1356
有刺的猬
有刺的猬 2021-01-14 13:46

I am forcing the download of an image through my website.

Forced download works fine on Apache/Windows development machine.

However it pushes junk characters

相关标签:
3条回答
  • 2021-01-14 13:55

    Hat tip (and +1) to stillstanding, who pointed out using fifo, but I thought I'd provide an example here to help. This example requires the fifo extension installed, and has been hacked out and slightly modified from some other code of mine.

        $filename = 'blarg.jpg';
        $filepath = '/foo/bar/blarg.jpg';
        $finfo    = new finfo(FILEINFO_MIME);
        $mime     = $finfo->file($file);
    
        // Provide a default type in case all else fails
        $mime = ($mime) ? $mime : 'application/octet-stream';
    
        header('Pragma: public');
        header('Content-Transfer-Encoding: binary');
        header('Content-type: ' . $mime);
        header('Content-Length: ' . filesize($filepath));
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    
        header('Content-transfer-encoding: 8bit');
        header('Expires: 0');
        header('Pragma: cache');
        header('Cache-Control: private');
    
    0 讨论(0)
  • 2021-01-14 13:55

    You have an incorrect MIME type in the header. Use finfo so you can send the correct one instead of transmitting everything as an application/stream, otherwise browser behavior will be unpredictable.

    0 讨论(0)
  • 2021-01-14 14:07

    Shouldn't the Content-Type be set to image?

    0 讨论(0)
提交回复
热议问题