首页  >  文章  >  后端开发  >  php通过加http响应头强制用户下载

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

WBOY
WBOY原创
2016-07-25 08:46:111620浏览

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


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn