Skip to content

Instantly share code, notes, and snippets.

@roytanck
Last active October 14, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roytanck/972a8e48c80ba125dcddad49800feb90 to your computer and use it in GitHub Desktop.
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.
/**
* 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