有没有任何方法可以提供到文件的直接链接,并强制浏览器使用PHP下载它?
E.ghttp://www.website.com/directory/file.jpg
我们在这里处理的是巨大的文件,尤其是Chrome似乎在渲染图像时遇到了问题,所以用户在直接访问文件时看到的只是一个空白屏幕。尽管他们仍然可以在空白屏幕上右键单击并下载文件,但这很令人困惑。
我们过去常常从PHP输出文件,但遇到内存问题,所以改为提供直接链接。这些文件高达5GB左右,它们并不都是图像。我们有zip、PDF、PSD等
目前,该文件是通过PHP脚本请求的,该脚本接受文件的ID并获取其URL。然后,PHP脚本重定向到用户的文件的完整URL。
我们如何确保强制下载,并且不会遇到较大文件的内存问题?
感谢
只需使用X-Sendfile
,但需要先配置它。。。使用XSendFilePath
if (file_exists($file)) {
header("X-Sendfile: $file");
header("Content-Type: application/octet-stream");
header(sprintf("Content-Disposition: attachment; filename='"%s'"", basename($file)));
exit();
}
注意*在验证和提供文件之前,请确保$file
已正确转义
XSendFilePath
仅适用于Apache上的其他服务器请参阅:缓存由PHP 动态创建的HTTP响应
您需要为强制下载设置headers
$file = 'upload_directory_path/'.$image_name;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
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: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
<?php
//file path
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}