强制通过php下载文件下载文件
问题描述:
我试图编写一个脚本,用户可以通过它直接下载图像。
这里是我最终的代码,强制通过php下载文件下载文件
<?php
$fileContents = file_get_contents('http://xxx.com/images/imageName.jpg');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode("http://xxx.com/images/imageName.jpg"));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileContents));
ob_clean();
flush();
echo $fileContents;
exit;
?>
但每次我打的URL,它返回一个零个字节数据的文件浏览器上面的脚本。
你想帮我解决这个问题吗?
答
尝试以下
<?php
$file_name = 'file.png';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
?>
答
我注意到你在文件上,而不是在文件名本身的内容使用文件大小;
,如果它是你的代码将工作:
<?php
$filename = 'http://xxx.com/images/imageName.jpg';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean(); // not necessary
flush(); // not necessary
echo file_get_contents($filename); // or just use readfile($filename);
exit;
?>
是否要强制下载远程服务器上的文件? –
@DhruvPatel yes – Tarun
然后,其他服务器启用.htaccess可能会导致不允许直接从其他源访问文件。 –