Skip to content

Instantly share code, notes, and snippets.

@pokeb
Created September 13, 2008 11:23
Show Gist options
  • 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
@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