PHP获取Cookie模拟登录

一、定义Cookie存储路径(必须使用绝对路径

$cookie_file = dirname(__FILE__)."/cookie.curl.txt";

二、获取Cookie

将cookie存入文件

$url = "http://www.LRXIN.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
$content = curl_exec($ch);
curl_close($ch);

三、模拟浏览器获取验证码

取出cookie,一起提交给服务器,让服务器以为是浏览器打开登陆页面

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.LRXIN.com/getCheckpic.pho?rand=6836.185874812305');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_exec($ch);
curl_close($ch);

四、POST提交

$post = "name=2&userType=1&passwd=asdf&loginType=1&rand=6836&imageField.x=25&imageField.y=7";    
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.LRXIN.com/loginstudent.action");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$result=curl_exec($ch);
curl_close($ch);

五、到指定页面获取数据

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.LRXIN.com/accountcardUser.action");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);        
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
$html=curl_exec($ch);
// var_dump($html);
curl_close($ch);






发表评论

邮箱地址不会被公开。 必填项已用*标注