-
-
Save pixelbart/bffc652aef7e9b38ac247e63a231c959 to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
This file contains 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 | |
/** | |
* Generates random, secure bytes that will be used for the password. | |
* | |
* @param int $nbBytes | |
* @param bool $strong | |
* | |
* @return string | |
*/ | |
function get_random_bytes( $nbBytes = 32, $strong = true ) { | |
$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.' ); | |
} | |
} | |
/** | |
* Generates a random, secure password with the support of openssl. | |
* | |
* @param int $length | |
* | |
* @return string | |
*/ | |
function generate_password( $length = 16 ) { | |
return substr( preg_replace( "/[^a-zA-Z0-9]/", "", base64_encode( getRandomBytes( $length + 1 ) ) ), 0, $length ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment