【问题标题】:Unable to download file in php无法在php中下载文件
【发布时间】:2016-02-02 08:11:24
【问题描述】:

我有一个文件下载代码using php,我在下载页面的代码如下。

 if (file_exists($strDownload)) {

    //get the file content
     $strFile = file_get_contents($strDownload);

       //set the headers to force a download
      header("Content-type: application/force-download");
     header("Content-Disposition: attachment; filename=\"" . str_replace(" ", "_", $arrCheck['file_name']) . "\"");

      //echo the file to the user
     echo $strFile;

     //update the DB to say this file has been downloaded
       mysql_query("xxxxxxxx");

           exit;
     }

函数file_exists() 通过有效检查,而我的$strDownload 变量将类似于位于服务器文件夹中的/home/public_html/uploads/myfile.zip。但是当我尝试下载文件而不是下载时,页面会显示文件的完整加密源。如何让它可下载?

编辑: 作为信息,我自己尝试在 wordpress 系统中使用这段代码,我的文件路径将类似于 http://example.com/wp-content/uploads/2016/02/myfile.zip。同样在上面提到的代码中,我自己检查了上面已经提到的服务器路径的file_exists() 条件,并根据需要返回1。

【问题讨论】:

标签: php download force-download


【解决方案1】:

试试这个

        if (file_exists($file)) 
        {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }

【讨论】:

  • 与问题中提到的结果相同。显示文件的源代码而不是下载。
【解决方案2】:

通过在php页面开头使用上述代码解决。即在声明著名的wordpress标签之前get_header();

如果我们在wordpress的get_header();标签之后使用上面的代码,它会导致页面首先打开,因此它会在页面中写入文件的源而不是下载,因为已经设置了元标签。

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2017-07-01
    • 2018-09-05
    相关资源
    最近更新 更多