使用 PHP + cURL 自动登录

罗纳德·纳瓦雷特

我正在尝试在华为路由器 (HG150-U) 上使用 cURL 和 PHP 登录,我有凭据。显然,当您从浏览器登录时,会创建 3 个 cookie。其中两个是登录的用户名和密码,但第三个是SESSIONID的名称,我搜索了更多,我找不到它的生成位置。

注意:貌似cookie是在发送请求的时候生成的。

查询看起来像这样 查询截图

亚历克斯·豪恩斯基

会话 ID 是不可预测的,这就是重点。(嗯,它不应该是,但它很短。)所以,不要自己创建 cookie。相反,在你的 curl 选项中设置一个 CURLOPT_COOKIEJAR,将它指向一个临时文件,然后通过传递用户/密码点击登录页面,它将在你的 jar 文件中创建 cookie。然后向您想要的数据页面发出第二个 curl 请求,现在在 CURLOPT_COOKIEFILE 中使用该文件,curl 将传递从上次命中创建并存储在 jar 中的 cookie。像这样的东西:

// Send user/password to the login page so that we get new cookies.
$curl = curl_init('<whatever the login page url is>');
curl_setopt($curl, CURLOPT_COOKIEJAR, '/tmp/cookies'); // cookies get stored in this file
curl_setopt($curl, CURLOPT_POSTFIELDS, [
    '<username field>' => '<username>',
    '<password field>' => '<password>',
]);
curl_setopt(...);
curl_exec($curl);
curl_close($curl);

// Send the cookies we just saved to the data page you want
$curl = curl_init('<whatever the data page url is>');
curl_setopt($curl, CURLOPT_COOKIEFILE, '/tmp/cookies'); // cookies in this file get sent
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt(...);
$page = curl_exec($curl);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章