我需要用php登录到另一个站点,然后从该站点的另一个页面获取内容,因为登录后它会转到主页,我需要客户页面。 我尝试使用 file_get_contents 和 curl,但众所周知,后者在这里使用 php curl 的代码更好:
$username='username';
$password='password';
$cookie="/home/cookie.txt";
$url = 'http://the-site.com/';
$postdata = "?&username=$username&password=$password&op=login&rUrl=?
op=customers";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
$result = curl_exec ($ch);
echo $result;
curl_close($ch);
op和rUrl是隐藏输入标签的名称。 如果我将$url+$postdata放在浏览器的地址栏中,它会转到所需的页面,但通过代码它没有按预期工作,它仍然保留在登录页面而不进入。
您的$postdata
似乎无效 - 它不应该有那个前导?&
。op
也出现了两次,第二次是op=customers
?
:
$postdata = "?&username=$username&password=$password&op=login&rUrl=?
op=customers";
此处建议使用http_build_query
,以确保生成精确的 URL 编码查询字符串,如下所示:
$postdata = [
'username' => $username,
'password' => $password,
'op' => 'login',
'rUrl' => 'customers',
];
echo '$postdata: ' . http_build_query($postdata);
exit;
设置:
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
它之所以有效,是因为:
CURLOPT_FOLLOWLOCATION TRUE 跟随服务器作为 HTTP 标头的一部分发送的任何 "Location: " 标头(请注意,这是递归的,PHP 将遵循发送的尽可能多的 "Location: " 标头,除非设置了CURLOPT_MAXREDIRS(。
登录后,它将被重定向到URL中指定的页面。