Skip to content

Instantly share code, notes, and snippets.

@printminion
Last active December 5, 2018 17:50
Show Gist options
  • Save printminion/5055906 to your computer and use it in GitHub Desktop.
Save printminion/5055906 to your computer and use it in GitHub Desktop.
Do cURL request to some API with cookie parsing
/**
* @desc Do cURL request to some API
* @author Misha M.-Kupriyanov https://plus.google.com/104512463398531242371/
* @link https://gist.github.com/5055906
*/
$currentSID = null;
$SESSION_NAME = '<PUT_YOUR_SESSION_NAME_HERE>';
$API_KEY = '<PUT_YOUR_API_KEY_HERE>';
$API_URL = 'http://host/api/v1/?alt=json'
$params = array(
$SESSION_NAME => $currentSID,
'apikey' => $API_KEY,
'method' => 'api.checkLoginStatus'
);
$result = doPostCall($API_URL, $params);
echo 'RESPONSE:' . print_r($result, true);
/*
* get current SessionID
*/
$currentSID = $result['cookies'][$SESSION_NAME];
echo '$currentSID:'.$currentSID.PHP_EOL;
function doPostCall($API_URL, $fields)
{
$fields_string = null;
print_r($fields);
//url-ify the data for the POST
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
echo 'URL:' . $url . PHP_EOL;
echo 'POST:' . $fields_string . PHP_EOL;
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
//curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//execute post
ob_start();
$postResult = curl_exec($ch);
$return = ob_get_contents();
ob_end_clean();
/*
* parse cookies
*/
preg_match('/^Set-Cookie:\s*([^;]*)/mi', $return, $m);
$returnArr['cookies'] = array();
if (count($m[1])) {
parse_str($m[1], $returnArr['cookies']);
}
/*
* get response
*/
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$returnArr['response'] = substr( $return, $header_size);
if (curl_errno($ch)) {
echo curl_error($ch) . PHP_EOL;
echo 'Unable to do request' . PHP_EOL;
return;
}
//close connection
curl_close($ch);
return $returnArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment