- strpos: documentation ( source)
- strtoupper: documentation ( source)
- dechex: documentation ( source)
- ord: documentation ( source)
<?php
class CookieCodec {
/**
* All characters valid in a cookie according to https://tools.ietf.org/html/rfc6265 and we have additionally
* removed % (used for escape sequences) and + (which, if not encoded, is interpreted as space in cookies by PHP,
* but there's no equivalent built-in JS decoding function, so we escape it to make decoding equivalent in both
* cases).
*/
private const COOKIE_CHARSET = '!#$&\'()*-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~';
public static function encode($string) {
$string = (string) $string;
$output = '';
for ($i = 0, $m = \strlen($string); $i < $m; $i++) {
$char = $string[$i];
if (\strpos(self::COOKIE_CHARSET, $char) === false) {
$ord = \ord($char);
$code = \strtoupper(\dechex($ord));
$output .= $ord > 15 ? "%$code" : "%0$code";
} else {
$output .= $char;
}
}
return $output;
}
}