PHP Password Strength Calculation


/ Published in: PHP
Save to your folder(s)

Copied it for later use hehe


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. /**
  4.  *
  5.  * @simple function to test password strength
  6.  *
  7.  * @param string $password
  8.  *
  9.  * @return int
  10.  *
  11.  */
  12. function testPassword($password)
  13. {
  14. if ( strlen( $password ) == 0 )
  15. {
  16. return 1;
  17. }
  18.  
  19. $strength = 0;
  20.  
  21. /*** get the length of the password ***/
  22. $length = strlen($password);
  23.  
  24. /*** check if password is not all lower case ***/
  25. if(strtolower($password) != $password)
  26. {
  27. $strength += 1;
  28. }
  29.  
  30. /*** check if password is not all upper case ***/
  31. if(strtoupper($password) == $password)
  32. {
  33. $strength += 1;
  34. }
  35.  
  36. /*** check string length is 8 -15 chars ***/
  37. if($length >= 8 && $length <= 15)
  38. {
  39. $strength += 1;
  40. }
  41.  
  42. /*** check if lenth is 16 - 35 chars ***/
  43. if($length >= 16 && $length <=35)
  44. {
  45. $strength += 2;
  46. }
  47.  
  48. /*** check if length greater than 35 chars ***/
  49. if($length > 35)
  50. {
  51. $strength += 3;
  52. }
  53.  
  54. /*** get the numbers in the password ***/
  55. preg_match_all('/[0-9]/', $password, $numbers);
  56. $strength += count($numbers[0]);
  57.  
  58. /*** check for special chars ***/
  59. preg_match_all('/[|!@#$%&*\/=?,;.:\-_+~^\\\]/', $password, $specialchars);
  60. $strength += sizeof($specialchars[0]);
  61.  
  62. /*** get the number of unique chars ***/
  63. $chars = str_split($password);
  64. $num_unique_chars = sizeof( array_unique($chars) );
  65. $strength += $num_unique_chars * 2;
  66.  
  67. /*** strength is a number 1-10; ***/
  68. $strength = $strength > 99 ? 99 : $strength;
  69. $strength = floor($strength / 10 + 1);
  70.  
  71. return $strength;
  72. }
  73.  
  74. /*** example usage ***/
  75. $password = 'php_tutorials_and_examples!123';
  76. echo testPassword($password);
  77.  
  78. ?>

URL: http://www.phpro.org/examples/Password-Strength-Tester.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.