PHP CURL 登陆

<?php
$testURL = 'http://www.test.com/show.asp?id=123';
$UserURL = 'http://www.test.com/userlogin.asp?action=login';
$UserData = array('username'=>'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/415/

posted @ 2013-09-10 17:45  My Game  阅读(283)  评论(0编辑  收藏  举报