PHP file download example code

WBOY
Release: 2016-07-25 09:11:57
Original
980 people have browsed it

Use php to implement forced downloading of files, and header functions are often used. Example, php file download example.

  1. class Downfile {
  2. function downserver($file_name){
  3. $file_path = "./img/".$file_name;
  4. //Transcoding, the file name is converted to gb2312 to solve Chinese garbled characters
  5. $file_name = iconv("utf-8","gb2312",$file_name);
  6. $file_path = iconv("utf-8","gb2312",$file_path);
  7. $fp = fopen($file_path," r") or exit("File does not exist");
  8. //Define the size of each download by leaving the variable empty
  9. $buffer = 1024;
  10. //Get the size of the file
  11. $file_size = filesize($file_path);
  12. / /header("Content-type:text/html;charset=gb2312");
  13. //Will write the four http protocol information used
  14. header("Content-type:application/octet-stream");
  15. header(" Accept-Ranges:bytes");//You can ignore it
  16. header("Content-Length: ".$file_size);//The original text here is Accept-Length. After checking the http protocol, there is no such item
  17. header("Content-Disposition:attachment ;filename=".$file_name);
  18. //Byte counter, records the current number of bytes
  19. $count = 0;
  20. while(!feof($fp) && $file_size-$count>0){
  21. / /Read $buffer-sized data each time from the file stream opened by $fp
  22. $file_data = fread($fp,$buffer);
  23. $count+=$buffer;
  24. //Read the read data
  25. echo $file_data;
  26. }
  27. //Close the file stream
  28. fclose($fp);
  29. }
  30. }
  31. ?>
Copy code

Call this function to pass in the file name to download the file. Pay attention to modifying $file_path in the above code.



Related labels:
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