欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-03-16 18:21:41
...

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