Skip to content

Instantly share code, notes, and snippets.

@jacquelineIO
Created June 18, 2018 18:53
Show Gist options
  • Save jacquelineIO/0f0cec7e7392dc006a9d3747f0c7d7e0 to your computer and use it in GitHub Desktop.
Save jacquelineIO/0f0cec7e7392dc006a9d3747f0c7d7e0 to your computer and use it in GitHub Desktop.
How to generate a token in PHP (copied from: https://security.stackexchange.com/a/40312)
<?php
function generateToken($length = 24) {
if(function_exists('openssl_random_pseudo_bytes')) {
$token = base64_encode(openssl_random_pseudo_bytes($length, $strong));
if($strong == TRUE)
return strtr(substr($token, 0, $length), '+/=', '-_,'); //base64 is about 33% longer, so we need to truncate the result
}
//fallback to mt_rand if php < 5.3 or no openssl available
$characters = '0123456789';
$characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
$charactersLength = strlen($characters)-1;
$token = '';
//select some random characters
for ($i = 0; $i < $length; $i++) {
$token .= $characters[mt_rand(0, $charactersLength)];
}
return $token;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment