Skip to content

Instantly share code, notes, and snippets.

@pokeb
Created September 13, 2008 11:23
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save pokeb/10590 to your computer and use it in GitHub Desktop.
Save pokeb/10590 to your computer and use it in GitHub Desktop.
Quick and dirty HTTP cookie header parser in PHP
@abcarroll
Copy link

Note that there is pecl_http, http_parse_cookie(). Although your's is far more portable.

@fastesol
Copy link

fastesol commented Jan 5, 2016

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 :(

@Rudde
Copy link

Rudde commented May 15, 2016

Seems like pecl_http is no more, so thanks a lot for this!

@sbonline
Copy link

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

@batiste93
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment