【问题标题】:[PHP]Download Code using header() not working[PHP]使用 header() 下载代码不起作用
【发布时间】:2015-09-12 03:10:16
【问题描述】:

我正在开发文件共享服务,我尝试制作下载代码,但只显示一个白页!

这里是down.php的代码

<?php
$var = $_GET["fid"];

        $fr = 'realname.txt'; //fake file name.
$filepath = '/home/user32222/public_html/parafile/'.$var.'/filestorage/downloadthisfile.txt' //In this case,  file extension is txt but I want to download file with any extension even file extension is nothing
//I tried these codes but it not worked!!
                    /*header('Pragma: public');     // required 
                    header('Expires: 0');       
                    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    header('Content-Type: application/octet-stream');
                    header("Content-Disposition: attachment; filename=\"$fr\"");
                    header('Content-Length: ' . filesize($filepath));
                    readfile($filepath);*/


                    $size   = filesize($filepath);
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename=' . $fr); //Download Client Program think file's name is realname.txt ($fr)

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


?>

【问题讨论】:

  • 您忘记了$fr = 'realname.txt 之后的报价。 '/home/user32222/public_html/parafile/'.$var.'/filestorage/downloadthisfile.txt' 之后也缺少分号
  • @PHPglue 哦,我错过了 ' 和 ;。但是现在不行了……
  • 打开错误报告看看 PHP 抛出了什么样的错误呢?到时候解决起来会容易很多!!!

标签: php download


【解决方案1】:

由于您没有阅读要下载的文件,因此返回空响应。这可以使用 readfile() 函数完成

试试这个代码:

<?php
     $var = $_GET["fid"];
     $fr = 'realname.txt'; //fake file name.
     $filepath =  '/home/user32222/public_html/parafile/'.$var.'/filestorage/downloadthisfile.txt';
     $size   = filesize($filepath);
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=' . $fr); 
     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);
     readfile($filepath);
?>

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2016-05-08
    • 2011-03-29
    相关资源
    最近更新 更多