php通过加http响应头强制用户下载

WBOY
發布: 2016-07-25 08:46:11
原創
1577 人瀏覽過

php中可以通过设置header的content-type,强制用户下载内容,而非直接在浏览器中打开,如下代码实现:

downloadFile.php

  1. $filename = $_GET['file']; //Get the fileid from the URL
  2. // Query the file ID
  3. $query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename));
  4. $sql = mysql_query($query);
  5. if(mysql_num_rows($sql) > 0){
  6. $row = mysql_fetch_array($sql);
  7. // Set some headers
  8. header("Pragma: public");
  9. header("Expires: 0");
  10. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  11. header("Content-Type: application/force-download");
  12. header("Content-Type: application/octet-stream");
  13. header("Content-Type: application/download");
  14. header("Content-Disposition: attachment; filename=".basename($row['FileName']).";");
  15. header("Content-Transfer-Encoding: binary");
  16. header("Content-Length: ".filesize($row['FileName']));
  17. @readfile($row['FileName']);
  18. exit(0);
  19. }else{
  20. header("Location: /");
  21. exit;
  22. }
  23. ?>
复制代码

files.php

复制代码

php, http


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!