强制下载文件通过PHP无法正常工作

时间:2013-01-18 06:12:52

标签: php html

我正在尝试编写一个脚本,用户可以通过该脚本直接下载图像 这是我最终的代码,

   <?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时,它返回一个零字节数据的文件 你想帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

尝试以下代码

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

答案 1 :(得分:0)

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

如果是以下代码,您的代码就会起作用:

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