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/
