强制通过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,它返回一个零个字节数据的文件浏览器上面的脚本。
你想帮我解决这个问题吗?

+0

是否要强制下载远程服务器上的文件? –

+0

@DhruvPatel yes – Tarun

+0

然后,其他服务器启用.htaccess可能会导致不允许直接从其他源访问文件。 –

尝试以下

<?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); 
?> 

Read more代码,请阅读本tutorial

+0

感谢它的工作,虽然它希望它与内容长度 – Tarun

+0

我很乐意帮助你 – Techie

我注意到你在文件上,而不是在文件名本身的内容使用文件大小;

,如果它是你的代码将工作:

<?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; 
?>