越简单越好!

php 下载文件

发表于 2006-08-16 12:37 | 1497次阅读 0次点赞   PHP

从网上看看了一些php下载文件的资料,改了改,写了这么个函数.

<?php
$url = "下载文件的地址";
$sgff = "要保存文件的本地目录";
$filename = "要保存为什么样的文件名";

$name= array_pop(explode(".", $url));  //获取后缀名'
$filename = $filename.".".$name;    //文件名后加入后缀'

function check_url($url){
	return preg_match("/^(http|ftp)(://)([a-zA-Z0-9-_]+[./]+[w-_/]+.*)+$/i", $url);
}
function down($url,$sgff,$filename){
	error_reporting(0);
	set_time_limit(0);
	$argv[1] = $url;
	$argv[2] = $sgff;
	//无参数则给出提示
	if (empty($argv[1])){
		echo "Usage: ". $argv[1] ." URL [Destination] ";
		exit();
	}

	//设置获取基本变量
	$url = $argv[1];
	echo "<b>Download >";
	$save_path = $argv[2] ? $argv[2] : "./";
	$file_name = $filename;
	$localfile = $save_path.$file_name;
	echo "<b>File path:</b>".$localfile."<br>";
	//检查变量
	if (!check_url($url)){
		exit("<b>Error: URL </b>". $url ." <b>invalid.</b> ");
	}
	if (file_exists($localfile)){
		exit("<b>Error: local file </b>". $localfile ." <b>exists.</b> ");
	}
	//打开远程文件
	$fp = fopen($url, "rb");
	if (!$fp){
		exit("<b>Error: Download </b>". $url ." <b>failed.</b> ");
	}

	//打开本地文件
	$sp = fopen($localfile, "wb");
	if (!$sp){
		exit("<b>Error: Open local file </b>". $localfile ." <b>failed.</b> ");
	}

	//下载远程文件
	echo "Downloading, please waiting... ";
	while (!feof($fp)){
		$tmpfile .= fread($fp, 512);
	}

	//保存文件到本地
	fwrite($sp, $tmpfile);
	fclose($fp);
	fclose($sp);
	echo "Download file ". $file_name ." succeed! ";

}

down($url,$sgff,$filename);
?>

返回顶部 ^