curl的多个动作

时间:2012-03-03 21:09:57

标签: php session curl

我正在尝试用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);

2 个答案:

答案 0 :(得分:4)

您可以使用相同的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);

以下是一些其他答案,显示如何在登录后使用cURL向同一站点发出多个串行请求 Login to Google with PHP and Curl, Cookie turned off?
Retrieve Android Market mylibrary with curl
PHP Curl - Cookies problem

答案 1 :(得分:0)

问题是通过使用curl_multi,您同时执行两个请求。表单提交请求将在登录请求的同时发送,因此登录cookie将不可用。

此外,您根本没有将cookie传递给表单请求。你忘了这样做:

curl_setopt($ch2, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch2, CURLOPT_COOKIEFILE, "cookie.txt");

您应该单独执行这两个请求,以确保表单请求可以使用正确的登录cookie。