0

我有一个使用 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根据需要返回。

4

2 回答 2

0

尝试这个

        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;
        }
于 2016-02-02T08:14:31.967 回答
0

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

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

于 2016-02-02T11:37:16.187 回答