A Simple PHP Password Generation Function

Page last updated on 2011 / 04 / 09

Passwords may well become a thing of the past in the not-so-distant future, as processing power doubles up year on year and makes the cracking of passwords in a brute force manner almost trivial.

This calculator of password complexity against brute force attacks shows how easy it is to compromise a password in an offline environment.

Fortunately for us web developers, things take an awful lot longer in an online scenario- mainly due to the fact that the online network is much slower than the electronics of a single box. Various other layers of protection can be added too, blaclistings IP's, locking accounts after a number of failed login attempts etc.

However, if somehow your filesystem/database gets compromised and becomes viewable by an untrusted source, you will hopefully have passwords encrypted!

If you are generating passwords for your users, you will want to have a level of complexity that won't be subject to brute force attacks.

The following code is a simple PHP password generator that will include alphanumeric characters and optionally other printable characters.

  1. <?php
  2.  
  3. function generate_password($length)
  4. {
  5. $chars = '.!,$%^&*@';
  6. $clen = strlen($chars);
  7. $password = substr(base_convert(substr(md5(microtime()),1),16,36),0,$length);
  8. $len = strlen($password);
  9. for($i = 0;$i < $len;$i++)
  10. {
  11. if(rand(0,1) & 1)
  12. $password[$i] = strtoupper($password[$i]);
  13. elseif(rand(0,2) & 1 && $clen)
  14. $password[$i] = $chars[rand(0,$clen)];
  15. }
  16. return $password;
  17. }
  18.  
  19. echo generate_password(10),"\n";
  20.  
  21. ?>

You can determine the length by passing it into the function. If you would prefer not to have the non-alphanumeric characters (they help increase the password complexity. Just change the $chars variable into an empty string.


Previous Article
Preventing E-Mail Header Injections with PHP mail()
Next Article
A Simple PHP .htpasswd Manager




Tweet