apache mod_xsendfile:讓php提供更快的檔案下載

來源:互聯網
上載者:User

伺服器提供一個檔案下載,一般使用一個url指向伺服器中的檔案即可提供下載。

但這樣就不能進行統計,許可權檢測等操作。

因此,一般使用php提供下載,代碼如下:

<?php  $file = 'test.zip';  if(file_exists($file)){      header('content-type:application/octet-stream');      header('content-disposition:attachment; filename='.basename($file));      header('content-length:'.filesize($file));      readfile($file);  }  ?>

處理中文檔案名稱:

<?php  $file = 'test.zip';  $filename = '中文.zip';        if(file_exists($file)){      $user_agent = $_SERVER['Http_User_agent'];      $encode_filename = rawurlencode($filename);            if(preg_match("/MSIE/", $user_agent)){          header('content-disposition:attachment; filename="'.$encode_filename.'"');      }else if(preg_match("/Firefox/", $user_agent)){          header("content-disposition:attachment; filename*=\"utf8''".$filename.'"');      }else{          header('content-disposition:attachment; filename="'.$filename.'"');      }      readfile($file);  }  ?>

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/

使用php readfile,需要經過php這層,如果可以直接通過apache將檔案發送給使用者,不經過php這層,將會提高下載速度。

使用apache mod_xsendfile,下載地址:mod_xsendfile,讓apache直接將檔案發給使用者

安裝:

sudo apxs2 -cia mod_xsendfile.c  sudo a2enmod xsendfile  sudo /etc/init.d/apache2 restart

apxs2 用於編譯apache module,需要安裝apache2-dev

設定xsendfile開啟:

<Directory>  XSendFile On  </Directory>

代碼如下:

<?php  $file = 'test.zip';  $filename = '中文.zip';        if(file_exists($file)){      $user_agent = $_SERVER['Http_User_agent'];      $encode_filename = rawurlencode($filename);            if(preg_match("/MSIE/", $user_agent)){          header('content-disposition:attachment; filename="'.$encode_filename.'"');      }else if(preg_match("/Firefox/", $user_agent)){          header("content-disposition:attachment; filename*=\"utf8''".$filename.'"');      }else{          header('content-disposition:attachment; filename="'.$filename.'"');      }      header('X-Sendfile:'.$file);  }  ?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.