-
-
Save cpxPratik/81aa019390a79e68bf4ba6446513aceb to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
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
<?php | |
private function get_random_bytes($nb_bytes = 32) | |
{ | |
$bytes = openssl_random_pseudo_bytes($nb_bytes, $strong); | |
if (false !== $bytes && true === $strong) { | |
return $bytes; | |
} | |
else { | |
throw new \Exception("Unable to generate secure token from OpenSSL."); | |
} | |
} | |
// usage: $password = generate_password(12); // for a 12-char password containing [0-9, a-z, A-Z] | |
private function generate_password($length){ | |
return substr( | |
preg_replace("/[^a-zA-Z0-9]/", "", base64_encode($this->get_random_bytes($length + 1))), | |
0, | |
$length | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment