PHP远程下载类

  1. <?php
  2. class download
  3. {
  4. var $url;//远程文件地址
  5. var $file_name = "hdwiki.zip";//下载来的文件名称
  6. var $save_path = "./updatefile";//下载到本地的文件路径
  7. var $localfile;//下载到本地文件的路径和名称
  8. var $warning;//警告信息
  9. var $redown=0;//是否重新下载
  10. /*初始化*/
  11. function seturl($url)
  12. {
  13. if(!emptyempty($url))$this->url = $url;
  14. }
  15. function setfilename($file_name)
  16. {
  17. if(!emptyempty($file_name))$this->file_name = $file_name;
  18. }
  19. function setsavepath($save_path)
  20. {
  21. if(!emptyempty($save_path))$this->save_path = $save_path;
  22. }
  23. function setredown($redown)
  24. {
  25. if(!emptyempty($redown))$this->redown = $redown;
  26. }
  27. function download($url, $redown = 0, $save_path = 0, $file_name = 0)
  28. {
  29. $this->seturl($url);
  30. $this->setfilename($file_name);
  31. $this->setsavepath($save_path);
  32. $this->setredown($redown);
  33. if(!file_exists($this->save_path))
  34. {
  35. $dir = explode("/",$this->save_path);
  36. foreach($dir as $p)
  37. mkdir($p);
  38. }
  39. }
  40. /* 检查url合法性函数 */
  41. function checkurl(){
  42. return preg_match("/^(http|ftp)(://)([a-za-z0-9-_]+[./]+[w-_/]+.*)+$/i", $this->url);
  43. }
  44. //下载文件到本地
  45. function downloadfile()
  46. {//开源代码phpfensi.com
  47. //检测变量
  48. $this->localfile = $this->save_path."/".$this->file_name;
  49. if($this->url == "" || $this->localfile == ""){
  50. $this->warning = "error: 变量设置错误.";
  51. return $this->warning;
  52. }
  53. if (!$this->checkurl()){
  54. $this->warning = "error: url ". $this->url ." 不合法.";
  55. return $this->warning;
  56. }
  57. if (file_exists($this->localfile)){
  58. if($this->redown)
  59. {
  60. unlink($this->localfile);
  61. }
  62. else
  63. {
  64. $this->warning = "warning: 升级文件 ". $this->localfile ." 已经存在! <a href='?action=download&redown=1' target='_self'>重新下载</a>";
  65. return $this->warning;
  66. //exit("error: 本地文件 ". $this->localfile ." 已经存在,请删除或改名后重新运行本程序.");
  67. }
  68. }
  69. //打开远程文件
  70. $fp = fopen($this->url, "rb");
  71. if (!$fp){
  72. $this->warning = "error: 打开远程文件 ". $this->url ." 失败.";
  73. return $this->warning;
  74. }
  75. //打开本地文件
  76. $sp = fopen($this->localfile, "wb");
  77. if (!$sp){
  78. $this->warning = "error: 打开本地文件 ". $this->localfile ." 失败.";
  79. return $this->warning;
  80. }
  81. //下载远程文件
  82. //echo "正在下载远程文件,请等待";
  83. while (!feof($fp)){
  84. $tmpfile .= fread($fp, 1024);
  85. //echo strlen($tmpfile);
  86. }
  87. //保存文件到本地
  88. fwrite($sp, $tmpfile);
  89. fclose($fp);
  90. fclose($sp);
  91. if($this->redown)
  92. $this->warning = "success: 重新下载文件 ". $this->file_name ." 成功";
  93. else
  94. $this->warning = "success: 下载文件 ". $this->file_name ." 成功";
  95. return $this->warning;
  96. }
  97. }
  98. ?>