PHP Swoole setcookie urlencode and base64 alternative

One issue Ive ran into recently: Swoole and Openswoole use urlencode to encode cookies when one invokes Swoole\Http\Response->cookie() method instead of rawurlencode. While swoole offers an alternative in form of rawCookie ( and then you could encode value as you wish) – not all depnedent frameworks and libraries support that: https://openswoole.com/docs/modules/swoole-http-response-cookie

Some popular PHP libraries for handling cookies with PSR7 responses – like Dflydev\FigCookies\SetCookies – use urlencode instead of rawurlencode for cookie value encoding at least at this moment.

Mezzio framework + swoole at least at the moment uses swoole+cookie instead of swoole+rawCookie – which means cookies will also be urlencode’d by default – this is different from how PHP handles $_COOKIE processing by default (it uses rawurlencode).

Problem with this – urlencode is not compliant with RFC 3986. One particularly sticky issue is that urlencode converts spaces into plus characters.

This may or may not be the problem for your particular use-case.

Unfortunately many people are also using base64 encoding to safeguard data for cookies – which also uses plus characters for its encoding. What happens when someone first encodes their data for cookies with base64 and then submits cookie using urlencode is -> data is likely will be irreversibly damaged as some plus characters would be there as a results of space => plus conversion and some are result of “data” => “base64 encoding”. Attempts of decoding such mangled data using base64_decode will fail.

If anyone was using base64_encode and base64_decode for data in cookies – you could use this non standard base64 encoding instead (this variant of base 64 doesn’t use + character and is url safe):

sodium_base642bin($base64String, SODIUM_BASE64_VARIANT_URLSAFE);
sodium_bin2base64($binaryString, SODIUM_BASE64_VARIANT_URLSAFE);

Thanks for reading.

Leave a Comment