Skip to content

Instantly share code, notes, and snippets.

@pixelbart
Forked from zyphlar/generatePassword.php
Last active February 18, 2020 15:40
Show Gist options
  • Save pixelbart/bffc652aef7e9b38ac247e63a231c959 to your computer and use it in GitHub Desktop.
Save pixelbart/bffc652aef7e9b38ac247e63a231c959 to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
<?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