PHP如何获取Cookie并实现模拟登录

这篇文章主要介绍了PHP如何获取Cookie并实现模拟登录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下。

一、定义Cookie存储路径

必须使用绝对路径

$cookie_jar = dirname(__FILE__)."/pic.cookie";

二、获取Cookie

将cookie存入文件

  1. $url = "http://1.2.3.4/";
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, $url);
  4. curl_setopt($ch, CURLOPT_HEADER, 0);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  6. curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
  7. $content = curl_exec($ch);
  8. curl_close($ch);

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

该服务器验证码有漏洞,可以自己指定

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

  1. $ch = curl_init();
  2. curl_setopt($ch, CURLOPT_URL, 'http://1.2.3.4/getCheckpic.action?rand=6836.185874812305');
  3. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
  4. curl_setopt($ch, CURLOPT_HEADER, 0);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6. $ret = curl_exec($ch);
  7. curl_close($ch);

四、POST提交

  1. $post = "name=2&userType=1&passwd=asdf&loginType=1&rand=6836&imageField.x=25&imageField.y=7";
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, "http://1.2.3.4/loginstudent.action");
  4. curl_setopt($ch, CURLOPT_HEADER, false);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  6. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  7. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
  8. $result=curl_exec($ch);
  9. curl_close($ch);

五、到指定页面获取数据

  1. $ch = curl_init();
  2. curl_setopt($ch, CURLOPT_URL, "http://1.2.3.4/accountcardUser.action");
  3. curl_setopt($ch, CURLOPT_HEADER, false);
  4. curl_setopt($ch, CURLOPT_HEADER, 0);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
  6. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
  7. $html=curl_exec($ch);
  8. // var_dump($html);
  9. curl_close($ch);