setrawcookie
setrawcookie($name, $value, $options)
Sends a cookie to the browser just like setcookie(), only it does not encode the value. It is useful for values that are already encoded, such as a token in hexadecimal. Returns true, or false on failure.
Parameters
- $name – the name of the cookie.
- $value – the value, without commas, semicolons, spaces, tabs and line breaks.
- $options – optional, an array of expires, path, domain, secure, httponly, samesite (from PHP 7.3), just like with setcookie().
Examples
// the value is not encoded, encode it yourself
setrawcookie("token", rawurlencode("a b;c"), array("path" => "/", "httponly" => true, "samesite" => "Lax"));
echo implode("", preg_grep("/^Set-Cookie: token=/", headers_list())); // Set-Cookie: token=a%20b%3Bc; path=/; HttpOnly; SameSite=Lax
// setcookie() encodes the value itself
setcookie("token2", "a b;c");
echo implode("", preg_grep("/^Set-Cookie: token2=/", headers_list())); // Set-Cookie: token2=a%20b%3Bc
header_remove("Set-Cookie");
// a random token in hexadecimal does not need encoding:
// setrawcookie("csrf", bin2hex(random_bytes(16)), array("path" => "/", "secure" => true, "httponly" => true, "samesite" => "Strict"));
Things to watch out for
- A value with a comma, semicolon, space, tab or line break: PHP 7.4 prints a warning and returns false, PHP 8 throws a ValueError exception.
- Just like setcookie() it must run before the first output of the page.
- Send login cookies and tokens with the secure, httponly and samesite options.
Related functions:
setcookie()
rawurlencode()
header()
headers_list()