multiple actions with curl

后端 未结 2 770
轻奢々
轻奢々 2020-12-19 14:33

I\'m trying to do two actions with curl: 1. Login into admin page 2. Submit a form (add user) The first one go fine but the second show error as not loged in. Here is my c

相关标签:
2条回答
  • 2020-12-19 15:07

    You can perform both of these requests using the same cURL handle. The problem in using curl_multi_exec in this case is that each curl handle has different options and $ch2 does not reference any cookies.

    Also, curl_multi_exec performs the requests in parallel which means you may try to add the user before the login request is completed or even started.

    Try this instead, it illustrates logging in using $ch, and then using it again to add the user. If the server supports keep-alive, then you can add a keep-alive header and the same socket connection is re-used for the second request.

    $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);
    

    Here are some other answers showing how to make multiple serial requests to the same site using cURL after logging in.
    Login to Google with PHP and Curl, Cookie turned off?
    Retrieve Android Market mylibrary with curl
    PHP Curl - Cookies problem

    0 讨论(0)
  • 2020-12-19 15:17

    The problem is that by using curl_multi, you are executing both requests at the same time. The form submitting request will be sent at the same time as the login request, so the login cookies will not be available yet.

    Additionally, you're not passing the cookies to the form request at all. You forgot to do this:

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

    You should do both requests separately to ensure that the proper login cookies are available for the form request.

    0 讨论(0)
提交回复
热议问题