How to force file download with PHP

后端 未结 11 1733
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 23:13

I want to require a file to be downloaded upon the user visiting a web page with PHP. I think it has something to do with file_get_contents, but am not sure how

11条回答
  •  萌比男神i
    2020-11-21 23:33

    A modification of the accepted answer above, which also detects the MIME type in runtime:

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    header('Content-Type: '.finfo_file($finfo, $path));
    
    $finfo = finfo_open(FILEINFO_MIME_ENCODING);
    header('Content-Transfer-Encoding: '.finfo_file($finfo, $path)); 
    
    header('Content-disposition: attachment; filename="'.basename($path).'"'); 
    readfile($path); // do the double-download-dance (dirty but worky)
    

提交回复
热议问题