网上的很多模拟登录程序,大都是通过服务程序apache之类的运行,获取到验证码之后显示在网页上,然后填上再POST出去,这样虽然看起来很友好,但是既然模拟登录,登录后所干的事情就不一定是短时间完成的,所以这就要受到php最大执行时间的限制,而且有些操作还有可能权限不足。
本文提供了一个程序实例,思路就是获取到验证码之后把验证码存储为一个图片,然后程序休眠20秒,在20秒之后由用户手动查看图片,并把验证码填写到code.txt文件中,20秒休眠完成后,程序会读code.txt的验证码,这样再带着验证码进行登录操作。具体代码如下:
/** * 模拟登录 */ //初始化变量 $cookie_file = "tmp.cookie"; $login_url = "http://xxx.com/logon.php"; $verify_code_url = "http://xxx.com/verifyCode.php"; echo "正在获取COOKIE...\n"; $curlj = curl_init(); $timeout = 5; curl_setopt($curl, CURLOPT_URL, $login_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($curl,CURLOPT_COOKIEJAR,$cookie_file); //获取COOKIE并存储 $contents = curl_exec($curl); curl_close($curl); echo "COOKIE获取完成,正在取验证码...\n"; //取出验证码 $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $verify_code_url); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $img = curl_exec($curl); curl_close($curl); $fp = fopen("verifyCode.jpg","w"); fwrite($fp,$img); fclose($fp); echo "验证码取出完成,正在休眠,20秒内请把验证码填入code.txt并保存\n"; //停止运行20秒 sleep(20); echo "休眠完成,开始取验证码...\n"; $code = file_get_contents("code.txt"); echo "验证码成功取出:$code\n"; echo "正在准备模拟登录...\n"; $post = "username=maben&pwd=hahahaha&verifycode=$code"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file); $result=curl_exec($curl); curl_close($curl); //这一块根据自己抓包获取到的网站上的数据来做判断 if(substr_count($result,"登录成功")){ echo "登录成功\n"; }else{ echo "登录失败\n"; exit; } //OK,开始做你想做的事吧。。。。。
你可以看下是否有其它的http header没有模拟,比如Referer和User-Agent是否都能模拟浏览器的值,一个完整的请求是类似于这样的:
GET /home/pack/data/content?id=31,2399,13,30&asyn=1&t=0.03439752989200834&_req_seqid=0xa982225f0637c78a HTTP/1.1
Accept: */*
Accept-Language: zh-cn
Referer: www.baidu.com/
x-requested-with: XMLHttpRequest
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BTRS123401; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; MS-RTC LM 8)
Host: www.baidu.com
Connection: Keep-Alive
Cookie: XCXXXXX
$url = "localhost/post_output.php";
$post_data = array (
"foo" => "bar",
"query" => "Nettuts",
"action" => "Submit"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
结果