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