Home >Backend Development >PHP Tutorial >Detailed process analysis of downloading files in PHP

Detailed process analysis of downloading files in PHP

WBOY
WBOYOriginal
2016-07-25 08:58:45975browse
  1. header("Content-type:text/html;charset=utf-8");
  2. // $file_name="cookie.jpg";
  3. $file_name="Christmas Carnival.jpg ";
  4. //To solve the problem that Chinese cannot be displayed
  5. $file_name=iconv("utf-8","gb2312",$file_name);
  6. $file_sub_path=$_SERVER['DOCUMENT_ROOT']."marcofly/phpstudy /down/down/";
  7. $file_path=$file_sub_path.$file_name;
  8. //First determine whether the given file exists
  9. if(!file_exists($file_path)){
  10. echo "There is no such file";
  11. return ;
  12. }
  13. $fp=fopen($file_path,"r");
  14. $file_size=filesize($file_path);
  15. //The header needed to download the file
  16. Header("Content-type: application/octet -stream"); ​​
  17. Header("Accept-Ranges: bytes");
  18. Header("Accept-Length:".$file_size);
  19. Header("Content-Disposition: attachment; filename=".$file_name);
  20. $buffer=1024;
  21. $file_count=0;
  22. //Return data to the browser
  23. while(!feof($fp) && $file_count<$file_size){
  24. $file_con=fread($fp,$buffer);
  25. $file_count+=$buffer;
  26. echo $file_con;
  27. }
  28. fclose($fp);
  29. ?>
Copy code
Notes: The role of header("Content-type:text/html;charset=utf-8"): When the server responds to the browser's request, it tells the browser to display the content in UTF-8 encoding. Regarding the problem that the file_exists() function does not support Chinese paths: Because the PHP function is relatively early and does not support Chinese, so if the downloaded file name is in Chinese, it needs to be character encoding converted, otherwise the file_exists() function cannot recognize it. You can Use the iconv() function for encoding conversion. $file_sub_path() I use absolute paths, which are more efficient than relative paths. The role of Header("Content-type: application/octet-stream"): Through this code, the client browser can know the file form returned by the server The role of Header("Accept-Ranges: bytes"): tells the client that the file size returned by the browser is calculated in bytes The role of Header("Accept-Length:".$file_size): tells the browser the size of the file returned The role of Header("Content-Disposition: attachment; filename=".$file_name): tells the browser the name of the file returned The above four Header() are required fclose($fp) can output the last remaining data in the buffer to a disk file and release the file pointer and related buffers.


Statement:
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