Home >Backend Development >PHP Tutorial >Remote file download code_PHP tutorial
Remote file download code Here we provide you with a remote file download code. We can use PHP to download remote files to a local specified directory. The following is a code class for downloading remote server files.
Remote file download code
Here we provide you with a remote file download code. We can use the PHP tutorial to download remote files to the local specified directory. The following is a code class for downloading remote server files.
class download
{
var $url;//Remote file addressvar $file_name = "hdwiki.zip";//Downloaded file name
var $save_path = "./www.bKjia.c0m";//Download to local file path
var $localfile;//The path and name of the downloaded local file
var $warning;//Warning message
var $redown=0;//Whether to re-download
/*Initialization*/
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);
}
}
/* Check URL validity function */
Function checkurl(){
return preg_match("/^(http|ftp)(://)([a-za-z0-9-_]+[./]+[w-_/]+.*)+$/i", $this->url);
}//Download the file locally
function downloadfile()
{
//Detect variable$this->localfile = $this->save_path."/".$this->file_name;
if (!$this->checkurl()){
If($this->url == "" || $this->localfile == ""){
return $this->warning;
}
$this->warning = "error: url ". $this->url ." is illegal.";
return $this->warning;
}if (file_exists($this->localfile)){
If($this->redown)
{
unlink($this->localfile);
}
else
{
$this->warning = "warning: Upgrade file". $this->localfile ." Already exists! Redownload a>";
return $this->warning;
//exit("error: The local file ". $this->localfile ." already exists, please delete or rename it and re-run this program.");}
}//Open remote file
$fp = fopen($this->url, "rb");
if (!$fp){
$this->warning = "error: Failed to open remote file ".$this->url."";
return $this->warning;
}//Open local file
$sp = fopen($this->localfile, "wb");
If (!$sp){
$this->warning = "error: Opening local file ". $this->localfile ." failed.";
return $this->warning;
}//Download remote files
//echo "Downloading remote files, please wait";
while (!feof($fp)){
$tmpfile .= fread($fp, 1024);
//echo strlen($tmpfile);}
//Save the file locallyfwrite($sp, $tmpfile);
fclose($fp);
fclose($sp);
If($this->redown)
$this->warning = "success: Re-download the file ". $this->file_name ." Success";
else
$this->warning = "success: Download file ". $this->file_name ." Success";
Return $this->warning;
}
}