CookieValuePrefix.php
TLDR
This file contains the CookieValuePrefix
class, which provides methods for creating, removing, and validating cookie value prefixes.
Methods
create
This method creates a new cookie value prefix for the given cookie name using the provided key. It uses the hash_hmac
function to compute a hash of the cookie name with a constant value and the key, and appends a '|' character to the resulting hash. The resulting string is returned.
remove
This method removes the cookie value prefix from the given cookie value. It simply returns a substring of the cookie value starting from the 41st character.
validate
This method validates whether a cookie value contains a valid prefix. It takes the cookie name, cookie value, and key as parameters. It uses the str_starts_with
function to check if the cookie value starts with the prefix created by the create
method. If the prefix is valid, the method calls the remove
method to remove the prefix from the cookie value and returns the modified value. If the prefix is not valid, the method returns null.
<?php
namespace Illuminate\Cookie;
class CookieValuePrefix
{
/**
* Create a new cookie value prefix for the given cookie name.
*
* @param string $cookieName
* @param string $key
* @return string
*/
public static function create($cookieName, $key)
{
return hash_hmac('sha1', $cookieName.'v2', $key).'|';
}
/**
* Remove the cookie value prefix.
*
* @param string $cookieValue
* @return string
*/
public static function remove($cookieValue)
{
return substr($cookieValue, 41);
}
/**
* Validate a cookie value contains a valid prefix. If it does, return the cookie value with the prefix removed. Otherwise, return null.
*
* @param string $cookieName
* @param string $cookieValue
* @param string $key
* @return string|null
*/
public static function validate($cookieName, $cookieValue, $key)
{
$hasValidPrefix = str_starts_with($cookieValue, static::create($cookieName, $key));
return $hasValidPrefix ? static::remove($cookieValue) : null;
}
}