Skip to content

Instantly share code, notes, and snippets.

@bishopb
Created October 26, 2016 18:18
Show Gist options
  • Save bishopb/622b3cd55c82d2d9917626c1a9ece590 to your computer and use it in GitHub Desktop.
Save bishopb/622b3cd55c82d2d9917626c1a9ece590 to your computer and use it in GitHub Desktop.
<?php
/**
* Simple class to parse the contents of a cookie jar file created by the cURL extension.
*
* <code>
* $jar = new CurlCookieJar('/tmp/curl-cookies');
* foreach ($jar->getAllCookies() as $cookie) {
* if ($cookie->expires < time()) {
* echo "Cookie named {$cookie->name} has expired\n";
* }
* }
* </code>
*/
class CurlCookieJar
{
/**
* Create an instance of the cookie jar, using the contents of the cURL format
* cookie jar found at the given filepath.
*
* @param string $filepath
*/
public function __construct($filepath)
{
$this->filepath = $filepath;
}
/**
* Parse the cookie jar file and return all cookies within.
* @return array of \StdClass
*/
public function getAllCookies()
{
$lines = @file($this->filepath);
if (empty($lines)) {
return [];
}
$cookies = [];
foreach ($lines as $line) {
if (preg_match('/^\s*#/', $line)) {
continue;
}
$line = trim($line);
if (empty($line)) {
continue;
}
// https://curl.haxx.se/mail/archive-2005-03/0099.html
$parts = sscanf($line, "%s\t%s\t%s\t%s\t%s\t%s\t%s");
$cookie = new \StdClass;
$cookie->domain = $parts[0];
$cookie->tailmatch = $parts[1];
$cookie->path = $parts[2];
$cookie->secure = $parts[3];
$cookie->expires = $parts[4];
$cookie->name = $parts[5];
$cookie->value = $parts[6];
$cookies[] = $cookie;
}
return $cookies;
}
/**
* Looks through the cookie jar and returns the one cookie with the given name.
* @param string $name
* @return \StdClass|null
*/
public function getCookieByName($name)
{
foreach ($this->getAllCookies() as $cookie) {
if ($cookie->name === $name) {
return $cookie;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment