Last active
October 14, 2021 12:48
-
-
Save roytanck/972a8e48c80ba125dcddad49800feb90 to your computer and use it in GitHub Desktop.
Create a short, fairly unique, urlsafe id string for a given input. This uses (almost) all allowed urlsafe characters to maximize the possible number of values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create a short, fairly unique, urlsafe hash for the input string. | |
*/ | |
function generate_id( $input, $length = 8 ){ | |
// Create a raw binary sha256 hash and base64 encode it. | |
$hash_base64 = base64_encode( hash( 'sha256', $input, true ) ); | |
// Replace non-urlsafe chars to make the string urlsafe. | |
$hash_urlsafe = strtr( $hash_base64, '+/', '-_' ); | |
// Trim base64 padding characters from the end. | |
$hash_urlsafe = rtrim( $hash_urlsafe, '=' ); | |
// Shorten the string before returning. | |
return substr( $hash_urlsafe, 0, $length ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment