PHP头条
热点:

PHPCurl实现登陆采集


登陆采集,是指某些网页内容需要使用帐号登陆以后,才可以查看,传统的file_get_contents无法获取到登陆后才可查看的内容。
curl是PHP中一个强大的组件,可以实现HTTP协议的HEAD,GET,POST方式访问数据,通过POST即可模拟用户登陆,然后拿到SESSION再获取具体的页面。

注意事项:
1、网页编码问题,如果对方的网页编码与你的不一致,请自行使用iconv或mb_string进行编码转换。
2、COOKIE保存的路径必须是绝对路径,一开始测试的时候,在WINDOWS上怎么也保存不上COOKIE,请确认你的路径。

废话不多说,直接看代码:

'coldstar','password'=>'123456.');
$cookiepath = $_SERVER["DOCUMENT_ROOT"] .'\\' .MD5($UserURL);	//以登陆域名的MD5值设置为COOKIE文件名
$html = curl_post_contents($UserURL,$UserData,$cookiepath);	//模拟登陆
if($html){
	if(stripos($html,'登陆成功')){
		$html = curl_get_contents($testURL,True,$cookiepath);	//获取真正的内容
	}else{
		$html = '登陆失败';
	}
}
echo $html;


function curl_get_contents($url,$usecookie = 0,$cookiepath = ''){
	$userAgent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
	$referer = $url;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);				//设置访问的url地址
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);				//设置超时
	curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);	//用户访问代理 User-Agent
	curl_setopt($ch, CURLOPT_REFERER, $referer);		//设置 referer
	if($usecookie){
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiepath);	//COOKIE的存储路径,传送时使用
	}
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);		//跟踪301
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		//返回结果
	$r = curl_exec($ch);
	curl_close($ch);
	return $r;
}

function curl_post_contents($url,$data = array(),$cookiepath = ''){
	$userAgent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
	$referer = $url;
	if(!is_array($data) || !$url) return '';
	foreach($data as $key=>$value){$post .= urlencode($key).'='.$value.'&';}
	rtrim($post ,'&');
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);				//设置访问的url地址
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);				//设置超时
	curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);	//用户访问代理 User-Agent
	curl_setopt($ch, CURLOPT_REFERER, $referer);		//设置 referer
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);		//跟踪301
	curl_setopt($ch, CURLOPT_POST, 1);					//指定post数据
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);		//添加变量
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiepath);	//COOKIE的存储路径,返回时保存COOKIE的路径
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		//返回结果
	$r = curl_exec($ch);
	curl_close($ch);
	return $r;
}
?>

原文:http://www.yanghengfei.com/archives/506/

www.phpzy.comtrue/phpyy/7054.htmlTechArticlePHPCurl实现登陆采集 登陆采集,是指某些网页内容需要使用帐号登陆以后,才可以查看,传统的file_get_contents无法获取到登陆后才可查看的内容。 curl是PHP中一个强大的组件,可以实现...

相关文章

相关频道:

PHP之友评论

今天推荐