Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick and dirty HTTP cookie header parser in PHP
@abcarroll

This comment has been minimized.

Copy link

@abcarroll abcarroll commented Sep 12, 2015

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

@fastesol

This comment has been minimized.

Copy link

@fastesol 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

This comment has been minimized.

Copy link

@Rudde Rudde commented May 15, 2016

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

@sbonline

This comment has been minimized.

Copy link

@sbonline sbonline commented Jun 28, 2016

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

This comment has been minimized.

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