一个完整的 curl post登录带验证码的代码

<?php
$cookie_file = "tmp.cookie";//做一个放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);//获取到的内容作为变量存储,设置为1或者TRUE就不直接输出
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);//链接时间
curl_setopt($curl,CURLOPT_COOKIEJAR,$cookie_file);//获取COOKIE并存储,把获得到的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;
}

posted @ 2017-03-10 18:38  在下刘彦直  阅读(3747)  评论(0编辑  收藏  举报