Skip to content

Instantly share code, notes, and snippets.

@drakemccabe
Created September 2, 2016 18:24
Show Gist options
  • Save drakemccabe/43c00dfa802d1f2e132e5fec51474194 to your computer and use it in GitHub Desktop.
Save drakemccabe/43c00dfa802d1f2e132e5fec51474194 to your computer and use it in GitHub Desktop.
Send Cookies From Server
public function fetchUsername($url, $cookies = null, $returnCookie = false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($cookies){
$cookies = urldecode(http_build_query($_COOKIE, NULL, ';'));
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
}
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
list($header, $body) = explode("\r\n\r\n", $result, 2);
$end = strpos($header, 'Content-Type');
$start = strpos($header, 'Set-Cookie');
$parts = explode('Set-Cookie:', substr($header, $start, $end - $start));
$cookies = array();
foreach ($parts as $co) {
$cd = explode(';', $co);
if (!empty($cd[0]))
$cookies[] = $cd[0];
}
curl_close($ch);
if ($returnCookie){
return $cookies;
}
return json_decode($body);
}
}
print_r($this->fetchUsername('https://www.example.com/json', $_COOKIE, FALSE));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment