0

I am executing multiple API calls in PHP page using curl_multi_exec. But my problem is that I need to call an API before multiple executions. How can I keep the session alive in all of the calls?

The first Url creates the session that i need to maintain in the multi-curl requests too.

$ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $session_url );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST,           1 );
    curl_setopt($ch, CURLOPT_POSTFIELDS,     '{
                            "usuario": "abc",
                            "password": "password"
                        }' ); 
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');  
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); 
    curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

    $result=curl_exec($ch);
    curl_close($ch);
    
    
    
    
            $multiCurl = array();
            $result = array();
            $mh = curl_multi_init();

            $multiCurl[1] = curl_init();
            curl_setopt($multiCurl[1], CURLOPT_URL, $url1);
            curl_setopt($multiCurl[1], CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($multiCurl[1], CURLOPT_CUSTOMREQUEST, "GET");
            curl_multi_add_handle($mh, $multiCurl[1]);

            $multiCurl[2] = curl_init();
            curl_setopt($multiCurl[2], CURLOPT_URL, $url2);
            curl_setopt($multiCurl[2], CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($multiCurl[2], CURLOPT_CUSTOMREQUEST, "GET");
            curl_multi_add_handle($mh, $multiCurl[2]);

            $index=null;
            do {
            curl_multi_exec($mh,$index);
            } while($index > 0);
            // get content and remove handles
            foreach($multiCurl as $k => $ch) {
            $result[$k] = curl_multi_getcontent($ch);
            $decodedRes[$k] = json_decode($result[$k], true);
            curl_multi_remove_handle($mh, $ch);
            }


            curl_multi_close($mh);
    
  • Does this answer your question? [Keeping session alive with Curl and PHP](https://stackoverflow.com/questions/13020404/keeping-session-alive-with-curl-and-php) – Mike Doe Apr 23 '20 at 17:20
  • step 1 is to re-use cookies, which you already are, but i guess you're killing the session every time you re-login, so you should check if your existing cookies are already logged in before doing the login procedure – hanshenrik Apr 24 '20 at 09:46

0 Answers0