Alternatives to GUID with PHP

GUID stands for Globally Unique Identifier. It is a string of letters and numbers and useful to allow website visitors to access a site without needing a username and password because although the probability that a GUID will be duplicated is not zero, it is close enough to zero to be negligible.

In fact Wikipedia says that you would have to generate 2.71 Quintillion (an 18 digit number) GUIDs to have a 50% probability of a collision.

However a GUID isn’t pretty, they look like 204FA460-65C6-DAB0-C69E-013ECE71F5D0 which can be scary to non-technical users when used in a URL.

Here is a shorter alternative. https://eager.io/blog/how-long-does-an-id-need-to-be/ does the math to show that a 72 bit random number gives a one in million chance of a duplicate. That should be fine for most web applications. 72 bits is 9 bytes, so generate a 9 byte random number – this can’t be used in a URL yet because it’s binary data so the next step is to encode it somehow.

Encoding a 9 byte number in hexadecimal gives an 18 character string – we can do better than that because hex only uses 6 of the available letter characters. Base64 encoding uses more of the character set and can result in only 12 characters. One more problem is that Base64 can use + and / characters which have another meaning when used in a URL. You can urlencode these so VVOV+mA/SSD6 becomes VVOV%2BmA%2FSSD6 but then the string length creeps up again and it begins to look scary to visitors.

The alternative is a base64url_encode / decode function that substitutes other characters in the place of the URL sensitive ones. These can be found in the PHP manual http://php.net/manual/en/function.base64-encode.php#121767

This gives a final URL which could look like myapp/register/VVOV-mA_SSD6 which I think is sensibly short and not at all intimidating.

$bytes = random_bytes(9);
$b64 = base64url_encode($bytes);

function base64url_encode( $data ){
  return rtrim( strtr( base64_encode( $data ), '+/', '-_'), '=');
}

One Reply to “Alternatives to GUID with PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.