douwen8118 2012-02-14 01:18
浏览 76
已采纳

用php提供可下载的文件

It is common to server downloadable files which are located outside the public folder by PHP:

$fp = fopen($file,"r") ;
header("Content-Type: application/msword");
header('Content-Disposition: attachment; filename="'.$filename.'"');

while (! feof($fp)) {
    $buff = fread($fp,4096);
    echo $buff;
}

I have two questions:

  1. Comparing with static files served by web server (direct file URL); does this method needs more resources (memory and cpu), as PHP needs to read the file and deliver?

  2. How we can display some text on the page? As we defined header, we do not have html output of the php script.

  • 写回答

4条回答 默认 最新

  • dongzhanlian6289 2012-02-14 01:47
    关注

    1 Since you have to process the file with this script it require more resources than just normal download link. However this is depend on your needs. If you think these files need more security. Let's say only authenticated users can download the file and only the file belongs to him. Then you need to validate those. In such situation you need the code you have put in your question. If your files are open to the public then you can display direct link to the file may be locating them somewhere in public temporarily.

    2 I can suggest you two methods to perform this.

    Method 1 :

    You need javascript support to perform this kind of requirement in handy way. Assume you need to display some HTML on the page where the download is possible. You can create a page with the HTML you want and you can put a download button.

    <input type="button" name="cmdDownload" id="cmdDownload" value="Download" onclick="downloadFile('<?php echo $pathToTheFile; ?>');" />

    And you can keep hidden iframe to process the download.

    <iframe id="downloadFrame" style="display:none"></iframe>
    

    Assume your PHP download page is download.php.

    Then you can have a javascript function like this.

    <script type="text/javascript">
    function downloadFile(filepath) 
    {
        var ifrme = document.getElementById("downloadFrame");
        ifrme.src = "download.php?filepath="+filepath;
    }
    </script>
    

    Method 2:

    Other than above method you can use META Refresh as well.

    <meta http-equiv="Refresh" content="3;URL=<?php echo $fullHTTPathToYourFile ?>" />
    

    You can have HTML display with this too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?