PHP forces users to download by adding http response headers

WBOY
Release: 2016-07-25 08:46:11
Original
1577 people have browsed it

In PHP, you can set the content-type of the header to force users to download the content instead of opening it directly in the browser. This is achieved by the following code:

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. ?>
Copy code

files.php

Copy code

php, http


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!