我正在尝试使用 curl 执行两个操作: 1. 登录管理页面 2. 提交表单(添加用户) 第一个没问题,但第二个显示错误未登录。这是我的代码:
$ch1 = curl_init();
$ch2 = curl_init();
curl_setopt($ch1, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch1, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch1, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch1, CURLOPT_URL, "http://admin.example.com/admin");
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, "user=admin&pass=password");
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch1, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch2, CURLOPT_URL, "http://admin.example.com/admin/adduser");
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, "newu=demo&pass=password");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 1);
$mh = curl_multi_init();
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
// execute all queries simultaneously, and continue when all are complete
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
Run Code Online (Sandbox Code Playgroud)
您可以使用相同的 cURL 句柄执行这两个请求。curl_multi_exec在这种情况下使用的问题是每个 curl 句柄都有不同的选项,$ch2并且没有引用任何 cookie。
此外,curl_multi_exec并行执行请求,这意味着您可以尝试在登录请求完成甚至启动之前添加用户。
试试这个,它说明了使用 登录$ch,然后再次使用它来添加用户。如果服务器支持keep-alive,那么您可以添加一个keep-alive标头,并为第二个请求重新使用相同的套接字连接。
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, "http://admin.example.com/admin");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=admin&pass=password");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
$res = curl_exec($ch);
// check $res here to see if login was successful
curl_setopt($ch, CURLOPT_URL, "http://admin.example.com/admin/adduser");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "newu=demo&pass=password");
$res = curl_exec($ch);
// check $res to see that the user was successfully created
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
以下是一些其他答案,显示了
登录后如何使用 cURL 向同一站点发出多个串行请求。使用 PHP 和 Curl 登录 Google,Cookie 已关闭?
使用 curl PHP Curl检索 Android Market mylibrary
- Cookies 问题
| 归档时间: |
|
| 查看次数: |
4791 次 |
| 最近记录: |