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学习者快速成长!