欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php文件下载类代码,php文件下载处理类

程序员文章站 2022-06-15 20:10:55
...
  1. /*

  2. * 功 能: 文件下载
  3. */
  4. /**
  5. * 使用方法:$download = new Download();
  6. * //设置参数
  7. * $download->set_file_dir("c:/");
  8. * $download->set_file_name("boot.ini");
  9. * $download->set_read_bytes(1024);
  10. * //文件下载处理操作
  11. * $download->deal_with();
  12. * //判断文件是否存在
  13. * if($download->is_file_exist()){
  14. *echo "file_exist";
  15. *}else{
  16. *echo "file_not_exist";
  17. *}
  18. */
  19. class Download {
  20. private $file = null;//文件句柄
  21. private $file_dir = "";//文件所在的目录
  22. private $file_name = "";//文件名称
  23. private $file_exist = false;//表示文件是否存在, 缺省为不存在
  24. private $read_bytes = 0;//文件读取字节数
  25. private $mode = "r";//文件的访问类型
  26. public function __construct(){

  27. }
  28. public function __destruct(){

  29. if(null != $this->file){
  30. fclose($this->file);
  31. }
  32. }
  33. /**

  34. * 文件下载处理的操作
  35. */ bbs.it-home.org
  36. public function deal_with(){
  37. //文件全路径
  38. $file_path = $this->file_dir . $this->file_name;
  39. //检查文件是否存在

  40. if (file_exists($file_path)) {
  41. $this->file_exist = true;
  42. // 打开文件

  43. $this->file = fopen($file_path, $this->mode);
  44. // 输入文件标签

  45. Header("Content-type: application/octet-stream");
  46. Header("Accept-Ranges: bytes");
  47. Header("Accept-Length: " . filesize($file_path));
  48. Header("Content-Disposition: attachment; filename=" . $this->file_name);
  49. // 输出文件内容

  50. while(!feof($this->file))
  51. {
  52. $out = fread($this->file, $this->read_bytes);
  53. if(!get_magic_quotes_gpc())
  54. {
  55. echo $out;
  56. }
  57. else
  58. {
  59. echo stripslashes($out);
  60. }
  61. }
  62. //echo fread($file, filesize($file_dir . $file_name));
  63. }
  64. }
  65. /**

  66. * 返回值为 true 或 false, 通过其值判断文件是否存在
  67. */
  68. public function is_file_exist(){
  69. return $this->file_exist;
  70. }
  71. /**

  72. * 参数类型为字符串
  73. */
  74. public function set_file_dir($file_dir=""){
  75. $this->file_dir = $file_dir;
  76. }
  77. /**

  78. * 参数类型为字符串
  79. */
  80. public function set_file_name($file_name=""){
  81. $this->file_name = $file_name;
  82. }
  83. /**

  84. * 参数类型为整型
  85. */
  86. public function set_read_bytes($read_bytes=1024){
  87. $this->read_bytes = $read_bytes;
  88. }
  89. }
  90. ?>
复制代码