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

前端 未结 3 1384
有刺的猬
有刺的猬 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');
    

提交回复
热议问题