我需要用 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;
关于php外部站点登录然后转到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606771/