Reputation: 11
I am trying to send a multi curl request to an api in order to retrieve data. This specific api requires a proper JSESSIONID cookie to be passed into the headers for it to work correctly.
The function I am using to send the request is:
function sendMultiRequest($data) {
// initialize array of curl handles
$curl_handles = array();
// returned data
$result = array();
// initialize multi handle
$multi_handle = curl_multi_init();
//$cookie = generateCookie();
$headers = array(
'Content-type: application/json',
'Cookie: JSESSIONID=39DDF47143F20CA952555027CD5F5EA2'
);
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $key => $val) {
$curl_handles[$key] = curl_init();
curl_setopt($curl_handles[$key], CURLOPT_URL, $val);
curl_setopt($curl_handles[$key], CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handles[$key], CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_handles[$key], CURLOPT_COOKIESESSION, TRUE);
curl_multi_add_handle($multi_handle, $curl_handles[$key]);
}
// execute the handles
$running = null;
do {
curl_multi_exec($multi_handle, $running);
} while($running > 0);
// get content and remove handles
foreach($curl_handles as $key => $val) {
$result[$key] = json_decode(curl_multi_getcontent($val), TRUE);
curl_multi_remove_handle($multi_handle, $val);
}
// close curl_multi
curl_multi_close($multi_handle);
return $result;
}
I dont think it is the functions problem because my other multi requests work. But when I try to access the api, I don;t get data unless I pass in a correct JSESSIONID.
I know this because I am currently using the Advanced REST Client Google Chrome Extension and when I use the Cookie Request Header that the extension passes, the function works. However, the api credentials expire and so I need to programattically create and use a JSESSIONID.
I understand that I must use the curl opt COOKIEJAR and COOKIE somehow, but I am not too sure as I am new to this.
Upvotes: 1
Views: 6789
Reputation: 71384
You only use CURLOPT_COOKIESESSION
when you are trying to simulate the start of a new session. By doing this cURL will not load any session cookies from the cookie jar/file.
You also need to specify the cookie jar file to be used via CURLOPT_COOKIEJAR
So building on your example:
// then add them to the multi-handle
foreach ($data as $key => $val) {
$curl_handles[$key] = curl_init();
curl_setopt($curl_handles[$key], CURLOPT_URL, $val);
curl_setopt($curl_handles[$key], CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handles[$key], CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_handles[$key], CURLOPT_COOKIEJAR, '/path/to/cookie/file');
// do this only if you need to force a new session and not load session cookie from cookie jar
curl_setopt($curl_handles[$key], CURLOPT_COOKIESESSION, TRUE);
curl_multi_add_handle($multi_handle, $curl_handles[$key]);
}
You should NEVER have to manually set your session id cookie value.
Upvotes: 2