3v4l.org

run code in 300+ PHP versions simultaneously
<?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; } }

preferences:
49.12 ms | 402 KiB | 5 Q