Home > Backend Development > PHP Tutorial > How to download files in php, the correct way to download php files

How to download files in php, the correct way to download php files

WBOY
Release: 2016-07-25 08:51:31
Original
1992 people have browsed it
  1. // Check whether the form is completely filled out...
  2. if ($form_completed) {
  3. Header("Location: http://www.myweb.com/download/info_check.exe") ;
  4. exit;
  5. }
  6. ?>
  7. Or:
  8. Start downloading the file
Copy the code

The ID method is used here to receive the number of the file to be downloaded, and then use " Redirect" method to connect to the actual URL.

For security reasons, users are not allowed to directly copy the URL to download the file. It is recommended to use PHP to directly read the actual file and then download it.

Code:

  1. $file_name = "info_check.exe";
  2. $file_dir = "/public/www/download/";
  3. if (!file_exists($file_dir . $file_name)) { //Check Whether the file exists
  4. echo "File not found";
  5. exit;
  6. } else {
  7. $file = fopen($file_dir . $file_name,"r"); // Open the file
  8. // Enter the file label
  9. Header(" Content-type: application/octet-stream");
  10. Header("Accept-Ranges: bytes");
  11. Header("Accept-Length: ".filesize($file_dir . $file_name));
  12. Header("Content- Disposition: attachment; filename=" . $file_name);
  13. // Output file content
  14. echo fread($file,filesize($file_dir . $file_name));
  15. fclose($file);
  16. exit;}
  17. ?>
Copy the code

And if the file path is an "http" or "ftp" URL, the source code will change slightly. The procedure is as follows:

  1. $file_name = "info_check.exe";
  2. $file_dir = "http://www.jincai123.com/";
  3. $file = @ fopen($file_dir . $file_name," r");
  4. if (!$file) {
  5. echo "File not found";
  6. } else {
  7. Header("Content-type: application/octet-stream");
  8. Header("Content-Disposition: attachment ; filename=" . $file_name);
  9. while (!feof ($file)) {
  10. echo fread($file,50000);
  11. }
  12. fclose ($file);
  13. }
  14. ?>
Copy Code

Using the above code, you can use php to directly output the file.



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