第一种情况,没有设置CURLOPT_FOLLOWLOCATION默认则不会跳转,当我们访问1.php的时候模拟访问了2.php不会跳转显示3.php的内容而是显示没有跳转,这里是2.php。
//1.php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://m.cn/2.php');
curl_setopt($curl, CURLOPT_HEADER, 0);
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($curl);
curl_close($curl);
//2.php
header("Location:3.php");
echo '没有跳转,这里是2.php';
//3.php
echo '这里是3.php';
第二种情况,如果设置CURLOPT_FOLLOWLOCATION为1(也就是把1.php里面注释的那行打开就OK了),则会跳转,当我们访问1.php的时候模拟访问了2.php就会跳转显示3.php的内容了。
今天遇到一个情况,真实登录https://git.oschina.net之后会302跳转到个人中心的页面,而我想获取登录后的个人中心的页面内容,所以我在curl登录https://git.oschina.net的时候尝试着把CURLOPT_FOLLOWLOCATION设置为1,但是发现就无法登录了。陷入了无限的死循环似乎。
$data = 'user[login]=i@zhoumengkang.com&user[password]=123456&user[remember_me]=0';
$cookie = dirname(__FILE__).'/os.cookie';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://git.oschina.net/login');
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_MAXREDIRS, 1)
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencode; charset=utf-8',
'Content-length:'.strlen($data)
));
// 去掉验证
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($curl);
反而把CURLOPT_FOLLOWLOCATION去掉或者设置为0,就好了。分两次curl,第一次去登陆,第二次去访问个人中心。为什么前面的那个方法不行呢?
老师给我的答案是:http是无状态的,我们不需要遵循网站开发者的逻辑,找到我们需要的页面就行。这样的确是解决了问题,但是不明白为什么。
$data = 'user[login]=i@zhoumengkang.com&user[password]=123456&user[remember_me]=0';
$cookie = dirname(__FILE__).'/os.cookie';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://git.oschina.net/login');
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_MAXREDIRS, 1)
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencode; charset=utf-8',
'Content-length:'.strlen($data)
));
// 去掉验证
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($curl);
//print_r(curl_getinfo($curl));
curl_close($curl);
// 登录后尝试获取页面内容
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://git.oschina.net/');
curl_setopt($curl, CURLOPT_POST, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:text/html'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
curl_exec($curl);
curl_close($curl);