PHP远程下载类
<?php
class?DownLoad
{
????var?$url;//遠程文件地址
????var?$file_name?=?"hdwiki.zip";//下載來的文件名稱
????var?$save_path?=?"./updatefile";//下載到本地的文件路徑
????var?$localfile;//下載到本地文件的路徑和名稱
????var?$warning;//警告信息
????var?$redown=0;//是否重新下載
????/*初始化*/
????function?setUrl($url)
????{
?????????if(!empty($url))$this->url?=?$url;
????}
????function?setFileName($file_name)
????{
?????if(!empty($file_name))$this->file_name?=?$file_name;
????}
????function?setSavePath($save_path)
????{
?????if(!empty($save_path))$this->save_path?=?$save_path;
????}
????function?setRedown($redown)
????{
?????if(!empty($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?." 已經存在! <a href='?action=download&redown=1' target='_self'>重新下載</a>";
????????????????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;
????}
}
?>?
轉載于:https://blog.51cto.com/3961409/809474
總結
- 上一篇: 将一张表里的数据转换为json字符串
- 下一篇: 常用的压缩归档命令