WpOrg\Requests

Cookie::parse()public staticWP 1.0

Parse a cookie string into a cookie object

Based on Mozilla's parsing code in Firefox and related projects, which is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265 specifies some of this handling, but not in a thorough manner.

Method of the class: Cookie{}

No Hooks.

Return

\WpOrg\Requests\Cookie. Parsed cookie object

Usage

$result = Cookie::parse( $cookie_header, $name, $reference_time );
$cookie_header(string) (required)
Cookie header value (from a Set-Cookie header)
$name(string)
-
Default: ''
$reference_time(int|null)
-
Default: null

Cookie::parse() code WP 6.6.2

public static function parse($cookie_header, $name = '', $reference_time = null) {
	if (is_string($cookie_header) === false) {
		throw InvalidArgument::create(1, '$cookie_header', 'string', gettype($cookie_header));
	}

	if (is_string($name) === false) {
		throw InvalidArgument::create(2, '$name', 'string', gettype($name));
	}

	$parts   = explode(';', $cookie_header);
	$kvparts = array_shift($parts);

	if (!empty($name)) {
		$value = $cookie_header;
	} elseif (strpos($kvparts, '=') === false) {
		// Some sites might only have a value without the equals separator.
		// Deviate from RFC 6265 and pretend it was actually a blank name
		// (`=foo`)
		//
		// https://bugzilla.mozilla.org/show_bug.cgi?id=169091
		$name  = '';
		$value = $kvparts;
	} else {
		list($name, $value) = explode('=', $kvparts, 2);
	}

	$name  = trim($name);
	$value = trim($value);

	// Attribute keys are handled case-insensitively
	$attributes = new CaseInsensitiveDictionary();

	if (!empty($parts)) {
		foreach ($parts as $part) {
			if (strpos($part, '=') === false) {
				$part_key   = $part;
				$part_value = true;
			} else {
				list($part_key, $part_value) = explode('=', $part, 2);
				$part_value                  = trim($part_value);
			}

			$part_key              = trim($part_key);
			$attributes[$part_key] = $part_value;
		}
	}

	return new static($name, $value, $attributes, [], $reference_time);
}