Skip to content

Instantly share code, notes, and snippets.

@fedir
Forked from zyphlar/generatePassword.php
Created June 7, 2017 18:41
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 fedir/4662cd863475eb08765ecf19e302949a to your computer and use it in GitHub Desktop.
Save fedir/4662cd863475eb08765ecf19e302949a to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
<?php
// usage: $newpassword = generatePassword(12); // for a 12-char password, upper/lower/numbers.
// functions that use rand() or mt_rand() are not secure according to the PHP manual.
function getRandomBytes($nbBytes = 32)
{
$bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
if (false !== $bytes && true === $strong) {
return $bytes;
}
else {
throw new \Exception("Unable to generate secure token from OpenSSL.");
}
}
function generatePassword($length){
return substr(preg_replace("/[^a-zA-Z0-9]/", "", base64_encode(getRandomBytes($length+1))),0,$length);
}
$pass = generatePassword(16);
echo $pass;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment