PHP Generate Unique Identifier Safe for URL and File Name
This code below shows how to generate a unique identifier that is safe for URLs and file names.
echo strtr(base64_encode(openssl_random_pseudo_bytes(16)), "+/=", "XXX");
/*
Example Output:
ZP7XlRcfgOPqy86dvfoXuQXX
IXoLIgHebRDPzyKArp1MtgXX
ZZehSdKBfvFKEvNSvbnEuQXX
*/
Explanation
First, the code uses openssl_random_pseudo_bytes to get cryptographically random data. We get 16 bytes of data for 128 bits of entrophy. It would be fairly hard for anyone to guess such a value.
Second, we encode the data using base64_encode. Normally, base64_encode converts the binary data to the characters from a-z, A-Z, 0-9, '+', '/', and '='. The three symbols there can cause problems in URLs and file names.
Since we are generating a unique identifier, we do not care about decoding the value. Therefore, the symbol characters '+', '/', and '=' can simply be translated to 'X's using strtr. We lose a little bit of entrophy by doing this, but it will not be much in most cases.
The result is an alphanumeric string containing a-z, A-Z, and 0-9 only. This will be safe to use in a file name, to be passed in a URL, embedded in HTML, saved in form data, etc. It can be used as a prefix or suffix without worrying about issues surrounding symbols and special characters.
Disclaimer: This content is provided as-is. The information may be incorrect.