远程文件下载代码

这里为各位提供一款远程文件下载代码,我们可以把远程的文件用php下载到本地指定的目录,下面就是一款下载远程服务器文件代码类。

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