Skip to content

Instantly share code, notes, and snippets.

@cpxPratik
Forked from zyphlar/generatePassword.php
Last active October 17, 2017 09:27
Show Gist options
  • Save cpxPratik/81aa019390a79e68bf4ba6446513aceb to your computer and use it in GitHub Desktop.
Save cpxPratik/81aa019390a79e68bf4ba6446513aceb to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
<?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