Home > Backend Development > PHP Tutorial > Sample code for php to implement file download and support Chinese file names

Sample code for php to implement file download and support Chinese file names

WBOY
Release: 2016-07-25 08:55:53
Original
788 people have browsed it
  1. /*----------------

  2. * $FileName is the file name, must be passed
  3. * $FilePath is the file path .Optional, it can be a relative path or an absolute path
  4. * @The path can only be composed of English and data, not Chinese
  5. * @Edited by: bbs.it-home.org
  6. --------- ---------*/
  7. header("Content-type: text/html;charset=utf-8");
  8. if(strlen($FileName)<=3){echo "Download failed : The file information you downloaded is incorrect";return;}
  9. $FileName=iconv("utf-8","gb2312",$FileName);//Convert the file name format to prevent Chinese garbled characters
  10. //Start Determine the path
  11. if(!is_null($FilePath)&&strlen($FilePath)>1){
  12. if(substr($FilePath,0,1)=='/'){//Determine whether it is an absolute path
  13. $FilePath =$_SERVER['DOCUMENT_ROOT'].$FilePath;
  14. }
  15. if(substr($FilePath,-1)!="/"){//Check whether the end is /
  16. $FilePath=$FilePath.'/' ;
  17. }
  18. if(is_numeric(strpos($FilePath,":"))){//Check whether it is an absolute path
  19. $FilePath=str_replace("/","",$FilePath);
  20. }
  21. }elseif( strlen($FilePath)==1&&$FilePath!="/"){
  22. $FilePath=$FilePath."/";
  23. }else{
  24. $FilePath="";
  25. }
  26. if(!file_exists($FilePath. $FileName)){
  27. echo "Download failed: The file to be downloaded was not found"; return;
  28. }
  29. /*-------------
  30. Send download related header information
  31. -- -----------=*/
  32. header("Content-type: application/octet-stream");
  33. header("Accept-Ranges: bytes");//Return according to byte size
  34. header("Accept-Length: $FileSize");//Return the file size
  35. header("Content-Disposition: attachment; filename=".$FileName);//The client's pop-up dialog box here, the corresponding file name< /p>
  36. /*-------------

  37. Start downloading related
  38. -------------=*/
  39. $FileSize=filesize( $FilePath.$FileName);
  40. $File=fopen($FilePath.$FileName,"r");//Open the file
  41. $FileBuff=512;
  42. while($FileSize>=0){
  43. $FileSize-=$ FileBuff;
  44. echo fread($File,$FileBuff);
  45. }
  46. fclose($File);
  47. }
  48. ?>

Copy code


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