这个函数也是项目中写的,提取出来,恐以后用到,还比较方便

 

/**
 * file_get_contents方式获取远程文件
 * @param $url 可以是带参数的url
 * @param $timeout 设置超时
 * @param $params 参数字符串,如a=2&b=3,通常用http_build_query生成
 * @param $method 'GET','POST','' 为空等表示不对参数处理
 * @param $times
 * @return string|boolean
 */
function get_remote_file($url = '', $timeout = 6, $params = '', $method = 'GET', $times = 3){
	//提交方式
	$method	=	strtoupper($method);
	//基本选项
	$opts['http'] = array(
			'method'=>$method,
			'timeout'=>$timeout,//设置超时时间(秒)
	);
	
	//判断参数提交方式
	if(!empty($params)){
		if('POST' == $method){
			$opts['http']['content']	=	$params;
		}elseif('GET' == $method){
				$url	.=	((false === strpos($url, '?'))?'?':'&').$params;
		}
	}
	$context	=	stream_context_create($opts);
	$cnt	=	0;
	$file	=	false;
	//尝试$times次获取远程文件
	while($cnt < $times && ($file = file_get_contents($url, false, $context)) === false)$cnt++;

	return $file;
}

 

posted on 2010-11-09 19:18  重生  阅读(1152)  评论(0编辑  收藏  举报