Are there any helper libs to read a cookie file in php. I have a cookie file on my local disk and I would like a better way of reading it. I am currently just reading to file like by line and parsing out the values.
7 Answers
This is pretty simple if you aim to read Netscape's format (e.g. curl saves cookies in COOKIEJAR in this format).
First an example (pipes and line numbers are added here and do not occur in real file):
01 | # Netscape HTTP Cookie File
02 | # http://curl.haxx.se/rfc/cookie_spec.html
03 | # This file was generated by libcurl! Edit at your own risk.
04 |
05 | .google.com TRUE / FALSE 1305843382 cookiename the value
06 | .yahoo.com TRUE / FALSE 1305843382 another_cookie it's value
07 |
As you can see:
- We might have comment lines denoted with
#
as the first character. - We might have blank lines
And then, the beefy lines each have 7 tokens separated with a tab character (\t
).
These are defined here:
- domain - The domain that created AND that can read the variable.
- flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
- path - The path within the domain that the variable is valid for.
- secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
- expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
- name - The name of the variable.
- value - The value of the variable.
So, now let's make our cookie-file parser.
// read the file
$lines = file('path/to/cookies.txt');
// var to hold output
$trows = '';
// iterate over lines
foreach($lines as $line) {
// we only care for valid cookie def lines
if($line[0] != '#' && substr_count($line, "\t") == 6) {
// get tokens in an array
$tokens = explode("\t", $line);
// trim the tokens
$tokens = array_map('trim', $tokens);
// let's convert the expiration to something readable
$tokens[4] = date('Y-m-d h:i:s', $tokens[4]);
// we can do different things with the tokens, here we build a table row
$trows .= '<tr></td>' . implode('</td><td>', $tokens) . '</td></tr>' . PHP_EOL;
// another option, make arrays to do things with later,
// we'd have to define the arrays beforehand to use this
// $domains[] = $tokens[0];
// flags[] = $tokens[1];
// and so on, and so forth
}
}
// complete table and send output
// not very useful as it is almost like the original data, but then ...
echo '<table>'.PHP_EOL.'<tbody>'.PHP_EOL.$trows.'</tbody>'.PHP_EOL.'</table>';
Finally, here is a demo.

- 37,241
- 25
- 195
- 267

- 29,356
- 21
- 76
- 127
-
1Note, that `$tokens[4]` could be `0`, if expires = session. – Serge S. Oct 17 '12 at 23:25
-
@OlegPopov you are more than welcome; this is all SO is about! – Majid Fouladpour Feb 08 '15 at 16:38
I could not find a code to cater for HttpOnly cookie records which is quite popular now - for example used in http://www.google.com/. An HttpOnly cookie is ONLY readable by browser and will remain hidden from all client side scripts like java scripts. You can find more details about HttpOnly cookies here.
Ignoring the format of these cookies in Netscape cookie files, will result in incorrect parsing. These records are prefixed with a "#HttpOnly_" string.
We should also "urldecode" parameter names and their values for almost all applications.
The following function is a combined and updated version of sample codes of Majid Fouladpour and Philip Norton which considers HttpOnly cookies and returns all cookies with their attributes in an array:
/**
* Extract any cookies found from the cookie file. This function expects to get
* a string containing the contents of the cookie file which it will then
* attempt to extract and return any cookies found within.
*
* @param string $string The contents of the cookie file.
*
* @return array The array of cookies as extracted from the string.
*
*/
function extractCookies($string) {
$lines = explode(PHP_EOL, $string);
foreach ($lines as $line) {
$cookie = array();
// detect httponly cookies and remove #HttpOnly prefix
if (substr($line, 0, 10) == '#HttpOnly_') {
$line = substr($line, 10);
$cookie['httponly'] = true;
} else {
$cookie['httponly'] = false;
}
// we only care for valid cookie def lines
if( strlen( $line ) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {
// get tokens in an array
$tokens = explode("\t", $line);
// trim the tokens
$tokens = array_map('trim', $tokens);
// Extract the data
$cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
$cookie['flag'] = $tokens[1]; // A TRUE/FALSE value indicating if all machines within a given domain can access the variable.
$cookie['path'] = $tokens[2]; // The path within the domain that the variable is valid for.
$cookie['secure'] = $tokens[3]; // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
$cookie['expiration-epoch'] = $tokens[4]; // The UNIX time that the variable will expire on.
$cookie['name'] = urldecode($tokens[5]); // The name of the variable.
$cookie['value'] = urldecode($tokens[6]); // The value of the variable.
// Convert date to a readable format
$cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);
// Record the cookie.
$cookies[] = $cookie;
}
}
return $cookies;
}
And this is a demonstration of the function.
This library allows you to manipulate (add, delete, update,...) Netscape Cookie File (eg. Cookies generated by CURL) :
https://github.com/kegi/netscape-cookie-file-handler
Simple example of reading + writing cookies:
/*Open and parse the cookie file*/
$configuration = (new Configuration())->setCookieDir('cookies/');
$cookieJar = (new CookieFileHandler($configuration))->parseFile('my_cookie_file');
/*Add (and save) a cookie*/
$cookieJar->add(
(new Cookie())
->setHttpOnly(true)
->setPath('/foo')
->setSecure(true)
->setExpire(new DateTime('2020-02-20 20:20:02'))
->setName('foo')
->setValue('bar')
)->persist();
P.S. This project is great, But I do not know why at this moment, its stars are so low! ;-)

- 9,887
- 6
- 59
- 81
I think $_COOKIE is what your looking for.
This superglobal can be used to read cookie data... to set it you need to use setcookie()
More can be found on the PHP website under $_COOKIE superglobal

- 7,432
- 4
- 26
- 28
I'm not sure I understand you correctly as it's normally pretty straightforward to set (using setcookie
) and read a cookie in PHP from your scripts:
$value = $_COOKIE['mycookie'];
If you are looking for a way of reading a raw cookie directly from your filesystem, without going through a browser, you'll need to specify what format/browser they were written in. The values could have been serialized from a lot of different languages and the end-result of the file might differ from browser to browser.
// Edit:
More on the browser differences: for example, Mozilla has a format like that and IE something more like that.

- 12,871
- 5
- 32
- 36
If you are using sessions in PHP, and you are in fact trying to parse the session data on disk, you can use the unserialize()
function on the contents of that file.

- 355
- 2
- 4