尝试让用户从服务器下载文件时,如下所示的常见解决方案可能不起作用:
header('Content-Description: File Transfer'); header('Content-Type: image/png'); header('Content-Disposition: attachment; filename="Image.png"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size); readfile("Image.png");
尽管控制台显示了正确的标题,但保存对话框可能不会出现。
关键错误在于 Content-Type 标头。对于文件下载,它不应该是 image/png,而是:
header('Content-Type: application/octet-stream');
文件下载的可靠标头集如下:
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\')); $size = filesize($file); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $quoted); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size);
通过确保正确发送标头后,当用户尝试从服务器下载文件时,系统将提示用户保存对话框。
以上是如何使用 PHP 标头可靠地强制文件下载?的详细内容。更多信息请关注PHP中文网其他相关文章!