问题概述:
通过php curl模拟登陆一个网站如http://www.aaa.com,通过fiddler抓包分析如下:
1、表单以POST方式提交到http://www.aaa.com/dologin,这里产生了一个token:xxx,
2、服务器带着这个token跳转到了以下地址来登陆:
https://account.usercenter.com/login?token=xxx&target_url=http://www.aaa.com;
(注意域名不同,并且是https,此外这个携带token的url拷贝到任何电脑都能正常登陆,登陆成功后就会失效)
3、登陆成功后地址重定向到target_url:http://www.aaa.com
问题分析:
我的理解:有一台授权服务器,任何一台PC电脑访问携带有效token的url,PC和服务器之间通过cookie来保持这个token;
提出问题:
使用php curl该如何实现这个登陆模拟?
以下是我的代码:
<?php $cookie_file = 'E:\work\cookie.txt'; $login_url = 'http://www.aaa.com/dologin'; $post_fields = 'userName=aa&password=bb&service_key=cc' $post_fields.= '&callback_url=http%3A%2F%2Fwww.aaa.com&hostUrl=http%3A%2F%2Fwww.aaa.com'; $ch = curl_init($login_url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); $contents=curl_exec($ch); curl_close($ch); preg_match('/(https:\/\/account\.usercenter\.com\/tokenLogin[^\s]*)\s*/',$contents,$match); //var_dump($match);die; 此处匹配出携带token的url $ch = curl_init($match[1]); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36 OPR/41.0.2353.46"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $result = curl_exec($ch); curl_close($ch); $url='http://www.aaa.com/1.html'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36 OPR/41.0.2353.46"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $contents = curl_exec($ch); curl_close($ch); var_dump($contents);//这里输出的页面显示没有登陆成功(这里是问题所在) ?>
不知通过cookie能不能实现这种登陆?各位大侠请指点~~