以下为本人工作中遇到的需要做的事情,之前也没怎么用过curl,查了好多资料,才稍微弄明白一点;本文所有内容只是自己平日工作的记录,仅供大家参考:
<?php
/**
* 模拟登录
*/
header("Content-type: text/html; charset=UTF-8");
//初始化变量
$cookie_file = "valid.tmp";
$login_url = "http://v3.gds.org.cn/login.aspx";
$verify_code_url = "http://v3.gds.org.cn/CheckCodeImg.aspx";
$curl = 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);
//取出验证码
$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);
$data = curl_exec($curl);
curl_close($curl);
//保存验证码图片
$fp = fopen("valid.jpg","wb");
fwrite($fp, $data);
fclose($fp);
//这里取出验证码图片后,程序休眠20s,这20s是用来手动查看验证码图片,然后把验证码手动写入当前目录下的code.txt文件中,等待后续读取
sleep(20);
//20s后开始读取刚才手动写入的验证码的TXT文件获得验证码
/*可下载验证码识别工具类,从而识别验证码,此处不再细说*/
$code = file_get_contents('code.txt');
//登录需要验证的参数,根据登录的网站要求而定
$post = array("__VIEWSTATE"=>'/wEPDwUKMjAxNzc1MTA0OA9kFgICAQ8WAh4GYWN0aW9uBQsvbG9naW4uYXNweBYEAgcPDxYCHghJbWFnZVVybAUgL0NoZWNrQ29kZUltZy5hc3B4P2lkPTIxMTk2ODAxMDNkZAIJDw9kFgIeB29uY2xpY2sFH0phdmFTY3JpcHQ6cmV0dXJuIExvZ2luQ2hlY2soKTtkZGMVVyyy1MfXv5mlHnNYOwIzMjm+sDJyRNMHE9LcjvgY',
"__VIEWSTATEGENERATOR"=>'C2EE9ABB',
"__EVENTVALIDATION"=>'/wEdAAUvG4CEDSAeffIfvT8/poMSt93hYdIOB6Ps/2Dq0TZfLrmXzh32huUyxvIXSZRQCCzJEpGhdun6s5y0mjTOD9huCal3PlhY9+LhlDAz50G/x28L/2U/T7kobvkKwEbiPO6upzznZuwcFVVFFeC+TWWb',
"UserID"=>'1444743',
"Pwd"=>'405769',
"KeyCode"=>$code,
"BTM"=>'');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $login_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_POST,1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
$result=curl_exec($curl);
curl_close($curl);
?>