<?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); | |
} |
no need to close tags actually :) From PHP Manual:
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
In fact @Cahl-Dee, closing tags in non-effect files (view code), is a really _Terrible_ practice, because it can cause effects
Be careful of the length!
String from base64_encode
may contain +
and /
characters. If you simply remove them by preg_replace
, there is chance the string length is shorter than $length
The variable $strong
in line 7 is not defined anywhere. Otherwise: Thank you very much for this!
Actually $strong is a passed-by-reference argument that is defined as a result of the function. Openssl uses it to tell you if the bytes are sufficiently random or not.
You're right, sorry! Thanks for your answer.
Thanks!
A minor improvement, for clearer intention and lower complexity:
if (false !== $bytes && true === $strong) {
return $bytes;
}
else {
throw new \Exception("Unable to generate secure token from OpenSSL.");
}
into
if (false !== $bytes && true === $strong) {
return $bytes;
}
throw new \Exception("Unable to generate secure token from OpenSSL.");
Thanks, excellent code, I will definitely use it in my projects :)
Close your php tag 😃