Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating secure passwords in PHP
<?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);
}
@Cahl-Dee

This comment has been minimized.

Copy link

Cahl-Dee commented Mar 30, 2015

Close your php tag 😃

@sclearion

This comment has been minimized.

Copy link

sclearion commented Apr 5, 2015

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.

@Lewiscowles1986

This comment has been minimized.

Copy link

Lewiscowles1986 commented Jul 6, 2015

In fact @Cahl-Dee, closing tags in non-effect files (view code), is a really _Terrible_ practice, because it can cause effects

@lacek

This comment has been minimized.

Copy link

lacek commented Jan 28, 2016

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

@pixelbart

This comment has been minimized.

Copy link

pixelbart commented Feb 18, 2020

The variable $strong in line 7 is not defined anywhere. Otherwise: Thank you very much for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.