php下载远程文件到服务器,模拟离线下载功能

1.如果服务器支持allow_url_fopen选项:


if ((boolean)ini_get('allow_url_fopen')){
	$url = '';
	$file = file_get_contents($url);
	$fp = fopen(basename($url), 'wb');
	fwrite($fp, $file);
	fclose($fp);
}

2.如果服务器支持Curl组件:


if (function_exists('curl_init')){
	$url = '';
	$ch = curl_init($url);
	$fp = fopen(basename($url), 'wb');
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_exec($ch);
	curl_close($ch);
	fclose($fp);
}

3.如果服务器支持fsockopen函数


if (function_exists('fsockopen')){
	$url = 'http://cn.wordpress.org/wordpress-3.7.1-zh_CN.zip';
	$url_info = parse_url($url);
	$host = $url_info['host'];
	$path = $url_info['path'];
	$fp = fsockopen($host, 80, $errno, $errstr, 30);
	if (!$fp) {
		echo "$errstr ($errno)<br />n";
	} else {
		$out = "GET ".$path." HTTP/1.1rn";
		$out .= "Host: ".$host."rn";
		$out .= "Connection: Closernrn";
		fwrite($fp, $out);
		$df = fopen(basename($path), 'w+');
		$i = 0;
		while(!feof($fp)){
			$fs = fgets($fp);
			if($i > 0){
				fwrite($df, $fs);
			}
			if($fs == "rn"){
				$i = 1;
			}
		}
		fclose($df);
		fclose($fp);
	}

}

发表评论