如何使文件可下载

时间:2013-08-05 17:44:22

标签: php download

我试图将文件下载添加到我的网站以获取音频视频和pdf文件 我使用php header()函数,但不是下载输出文件,而是继续下载php页面。这是我的代码。

    header('Content-disposition: attachment; 
            Content-type: audio/mpeg; 
            filename=thefile.type');

2 个答案:

答案 0 :(得分:0)

你需要写出文件的内容,例如

header('Content-disposition: attachment; 
   Content-type: audio/mpeg; 
   filename=thefile.type');
echo file_get_contents("thefile.type");

答案 1 :(得分:0)

这很好用

    if (file_exists("audio/thefile.type"))
    {
         if (FALSE!== ($handler = fopen('thefile.type', 'r')))
            {
             header('Content-Description: File Transfer');
             header('Content-Type: application/octet-stream');
             header('Content-Disposition: attachment; 
                     filename=audio/thefile.type');
             header('Content-Transfer-Encoding: chunked'); //changed to chunked
             header('Expires: 0');
             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
             header('Pragma: public');
             //header('Content-Length: ' . filesize('thefile.type')); //Remove

             //Send the content in chunks
             while(false !== ($chunk = fread($handler,4096)))
                  {
                    echo $chunk;
                  }
             }
             exit;
    }
    else{

           echo "<h1>Content error</h1><p>The file does not exist!</p>";
         }