Created
September 13, 2008 11:23
-
-
Save pokeb/10590 to your computer and use it in GitHub Desktop.
Quick and dirty HTTP cookie header parser in PHP
but pecl_http doesn't seams to work or at least I could not install it on my VPS (CentOS 5.7 - PHP 5.5.x) and couldn't find any solution on Internet :(
Seems like pecl_http is no more, so thanks a lot for this!
I stumble upon this thread in search for something fast (procedural-I'm in Drupal-7)
and since it was not what I was looking for; here attached different version.
function _get_cookie($search_str="") {
$data = array();
foreach (headers_list() as $header_item) {
if (strpos($header_item, 'Set-Cookie') !== FALSE) {
$data[]= _parse_cookie($header_item);
}
}
if (empty($data)){
return FALSE;
}
if ($search_str){
foreach ($data as $cookie){
if (strpos($cookie['key'], $search_str) === 0){
return $cookie;
}
}
}
return $data;
}
function _parse_cookie($c) {
if (strpos($c, ":") === FALSE)
return FALSE;
$c = explode(":", $c);
if (!isset($c[1]))
return FALSE;
$c = trim($c[1]);
if (strpos($c, ";") !== FALSE) {
$c = explode(";", $c);
if (!isset($c[0]))
return FALSE;
$c = trim($c[0]);
}
if (strpos($c, "=") === FALSE)
return FALSE;
$c = explode("=", $c);
if (!isset($c[0]) || !isset($c[1]))
return FALSE;
return array('key' => $c[0], 'value' => $c[1]);
}
So just use $cookies=_get_cookie();
or if you want specific cookie: $cookie = _get_cookie("PHPSESSID");
This is good alternative: https://github.com/guzzle/guzzle3/blob/master/src/Guzzle/Parser/Cookie/CookieParser.php
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that there is pecl_http, http_parse_cookie(). Although your's is far more portable.