$token = base64_encode( openssl_random_pseudo_bytes(32));
<input type="hidden" name="csrf_token" value="<?=$token?>">
Do I need to escape the $token
on output?
$token = base64_encode( openssl_random_pseudo_bytes(32));
<input type="hidden" name="csrf_token" value="<?=$token?>">
Do I need to escape the $token
on output?
There is no point in escaping base64 encoded data, by definition it won't have any control characters (or quotes etc.) inside.
Actually, you might. The problem lies in the fact that one of the base64 encoding characters, the one with index 62, is actually encoded by PHP as a plus character (+), and that plus might get URL-decoded as a space by the browser when sending it along (or rather, by something between the browser and the server - a proxy, a load balancer, a filter...).
Therefore, some data risks being encoded in a form that will then be decoded as a different string (and actually not be decoded at all, since space will break the base64 scheme).
Both modern Firefox and Chrome correctly encode that + into %2B (I just tested), and the standards seem to dictate that the + must always be encoded and base64 does not need further escaping but the problem arises in some cases (see URLs and plus signs ).
Rather than risking the token working 99.97% of the time (the 0.03% being the day you needed it the most, as Murphy rules), a simple workaround would be to convert the token to hexadecimal byte representation:
$token = bin2hex(openssl_random_pseudo_bytes(32));
<input type="hidden" name="csrf_token" value="<?=$token?>">