小编典典

如何在PHP中返回文件

php

我有一个档案

/file.zip

用户来

/download.php

我希望用户的浏览器开始下载文件。我怎么做?readfile是否在服务器上打开文件,这似乎是不必要的事情。有没有一种方法可以在不打开服务器的情况下返回文件?


阅读 564

收藏
2020-05-29

共1个答案

小编典典

我想你想要这个:

        $attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/file.zip";
        if (file_exists($attachment_location)) {

            header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
            header("Cache-Control: public"); // needed for internet explorer
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");
            header("Content-Length:".filesize($attachment_location));
            header("Content-Disposition: attachment; filename=file.zip");
            readfile($attachment_location);
            die();        
        } else {
            die("Error: File not found.");
        }
2020-05-29