简体   繁体   中英

PHP readfile() causing pdf to render in browser, not downloading

I'm trying to force a file download and all I get is a random string of unknown characters in the browser window. Code is included:

$file_url = "docs/$c/$path";
header('Content-Description: File Transfer');
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$title.$type");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Transfer-Encoding: binary");
header("Pragma: public");
header("Content-Length: ".filesize($file_url));
readfile($file_url);

It's been going on for about a week, I'm going nuts. Any help is appreciated. Thanks.

I suspect your Content-Disposition header is the problem.

Try this version instead:

header("Content-Disposition: attachment; filename=\"$title.$type\"");

I was facing the same error. Using ob_clean() and flush() helped my case. I used the code below:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename='.$filename.'.pdf');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-type: application/force-download');
header( 'Content-transfer-encoding: binary' ); 
ob_clean();
flush();
readfile('Reports/'.$filename.'.pdf');
exit;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM