<?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;
}
}
?>