PHP.GT

Cookie objects and validation

Cookie is a small immutable value object. It stores a cookie name and value, and refuses names or values that contain characters which are not valid for HTTP cookies.

Creating a Cookie object

use GT\Cookie\Cookie;

$cookie = new Cookie("currency", "GBP");

The value defaults to an empty string:

$empty = new Cookie("seenWelcome");

Reading the name and value

echo $cookie->getName();
echo $cookie->getValue();

The object can also be cast to a string, which returns the value:

echo "Selected currency: " . $cookie;

Immutability

Cookie objects do not expose setters. To change the value, use withValue():

$original = new Cookie("currency", "GBP");
$updated = $original->withValue("EUR");

echo $original->getValue(); // GBP
echo $updated->getValue(); // EUR

withValue() returns a clone, so the original object is unchanged.

Validation

Cookie names and values are restricted by the characters that are valid in HTTP cookie headers. The library performs this validation when a Cookie is constructed and when withValue() is called.

Invalid data throws InvalidCharactersException:

use GT\Cookie\Cookie;
use GT\Cookie\InvalidCharactersException;

try {
	$cookie = new Cookie("bad,name", "value");
}
catch(InvalidCharactersException) {
	echo "The cookie name or value contains characters that cannot be used.";
}

The exact character sets are exposed by Validity.

Validity helper

Validity can be used directly when we want to validate before constructing a Cookie:

use GT\Cookie\Validity;

if(!Validity::isValidName($name)) {
	throw new InvalidArgumentException("Invalid cookie name");
}

if(!Validity::isValidValue($value)) {
	throw new InvalidArgumentException("Invalid cookie value");
}

The helper also exposes the allowed characters as arrays:

$nameCharacters = Validity::getValidNameCharacters();
$valueCharacters = Validity::getValidValueCharacters();

Name characters are alphanumeric characters plus the allowed cookie-name punctuation. Value characters are alphanumeric characters plus the allowed cookie-value punctuation and a space.

Exceptions

All package-specific exceptions extend CookieException:

  • InvalidCharactersException is thrown when a cookie name or value is invalid.
  • CookieSetException is thrown when code tries to set a cookie through array assignment.

That means application code can catch the specific exception, or catch CookieException for any error raised by this package.


Next, see WebEngine usage for how this package fits into a PHP.GT application.