這里為各位提供一款遠程文件下載代碼,我們可以把遠程的文件用php下載到本地指定的目錄,下面就是一款下載遠程服務器文件代碼類。
- class download
- {
- var $url;//遠程文件地址
- var $file_name = "hdwiki.zip";//下載來的文件名稱
- var $save_path = "./www.49028c.com";//下載到本地的文件路徑
- var $localfile;//下載到本地文件的路徑和名稱
- var $warning;//警告信息
- var $redown=0;//是否重新下載
- /*初始化*/
- function seturl($url)
- {
- if(!emptyempty($url))$this->url = $url;
- }
- function setfilename($file_name)
- {
- if(!emptyempty($file_name))$this->file_name = $file_name;
- }
- function setsavepath($save_path)
- {
- if(!emptyempty($save_path))$this->save_path = $save_path;
- }
- function setredown($redown)
- {
- if(!emptyempty($redown))$this->redown = $redown;
- }
- function download($url, $redown = 0, $save_path = 0, $file_name = 0)
- {
- $this->seturl($url);
- $this->setfilename($file_name);
- $this->setsavepath($save_path);
- $this->setredown($redown);
- if(!file_exists($this->save_path))
- {
- $dir = explode("/",$this->save_path);
- foreach($dir as $p)
- mkdir($p);
- }
- }
- /* 檢查url合法性函數 */
- function checkurl(){
- return preg_match("/^(http|ftp)(://)([a-za-z0-9-_]+[./]+[w-_/]+.*)+$/i", $this->url);
- }
- //下載文件到本地
- function downloadfile()
- {
- //檢測變量
- $this->localfile = $this->save_path."/".$this->file_name;
- if($this->url == "" || $this->localfile == ""){
- $this->warning = "error: 變量設置錯誤.";
- return $this->warning;
- }
- if (!$this->checkurl()){
- $this->warning = "error: url ". $this->url ." 不合法.";
- return $this->warning;
- }
- if (file_exists($this->localfile)){
- if($this->redown)
- {
- unlink($this->localfile);
- }
- else
- {
- $this->warning = "warning: 升級文件 ". $this->localfile ." 已經存在! 重新下載";
- return $this->warning;
- //exit("error: 本地文件 ". $this->localfile ." 已經存在,請刪除或改名后重新運行本程序.");
- }
- }
- //打開遠程文件
- $fp = fopen($this->url, "rb");
- if (!$fp){
- $this->warning = "error: 打開遠程文件 ". $this->url ." 失敗.";
- return $this->warning;
- }
- //打開本地文件
- $sp = fopen($this->localfile, "wb");
- if (!$sp){
- $this->warning = "error: 打開本地文件 ". $this->localfile ." 失敗.";
- return $this->warning;
- }
- //下載遠程文件
- //echo "正在下載遠程文件,請等待";
- while (!feof($fp)){
- $tmpfile .= fread($fp, 1024);
- //echo strlen($tmpfile);
- }
- //保存文件到本地
- fwrite($sp, $tmpfile);
- fclose($fp);
- fclose($sp);
- if($this->redown)
- $this->warning = "success: 重新下載文件 ". $this->file_name ." 成功";
- else
- $this->warning = "success: 下載文件 ". $this->file_name ." 成功";
- return $this->warning;
- }
- }
新聞熱點
疑難解答