Password.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. /**
  3. * This file contains the class Password.
  4. * For more information on this file and how to use the class please visit
  5. * http://www.hashbangcode.com/blog/password-validation-class-in-php-2015.html
  6. *
  7. * PHP Version 5.0.0
  8. *
  9. * @category Password
  10. * @package Password
  11. * @author Philip Norton <philipnorton42@gmail.com>
  12. * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  13. * @link http://www.hashbangcode.com/
  14. */
  15. namespace PHPPassword;
  16. /**
  17. * This class can be used to validate a password or password like string to
  18. * certain standards. These can be things like having more than one letter,
  19. * or having at least a single number.
  20. * The class can also be used to "score" a password to certain parameters.
  21. *
  22. * @category Password
  23. * @package Password
  24. * @author Philip Norton <philipnorton42@gmail.com>
  25. * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  26. * @version Release: 1.0 04/09/2009
  27. * @link https://github.com/philipnorton42/PHP-Password
  28. *
  29. */
  30. class Password {
  31. /**
  32. *
  33. * @var array Holds an array of any errors encountered whilst validating
  34. * the password.
  35. */
  36. protected $errors = array();
  37. /**
  38. *
  39. * @var integer The minimum number of characters that the password must be.
  40. */
  41. protected $minLength = 7;
  42. /**
  43. *
  44. * @var integer The maximum number of characters that the password must be.
  45. */
  46. protected $maxLength = 15;
  47. /**
  48. *
  49. * @var integer The minimum number of numbers that the password should contain.
  50. */
  51. protected $minNumbers = 1;
  52. /**
  53. *
  54. * @var integer The minimum number of letters that the password should contain.
  55. */
  56. protected $minLetters = 5;
  57. /**
  58. *
  59. * @var integer The minimum number of lower case letters that the password
  60. * should contain.
  61. */
  62. protected $minLowerCase = 1;
  63. /**
  64. *
  65. * @var integer The minimum number of upper case letters that the password
  66. * should contain.
  67. */
  68. protected $minUpperCase = 1;
  69. /**
  70. *
  71. * @var integer The minimum number of symbols that the password should contain.
  72. */
  73. protected $minSymbols = 1;
  74. /**
  75. *
  76. * @var integer The maximum number of symbols that the password should contain.
  77. */
  78. protected $maxSymbols = 3;
  79. /**
  80. *
  81. * @var array The symbols that are allowed to be in the password.
  82. */
  83. protected $allowedSymbols = array('#', '_', '!');
  84. /**
  85. *
  86. * @var integer The score of the password.
  87. */
  88. protected $score = 100;
  89. /**
  90. * Constructor
  91. *
  92. * @param array $options An associative array of options.
  93. */
  94. public function __construct($options = array()) {
  95. // Pass options setting onto the setOptions() function.
  96. $this->setOptions($options);
  97. }
  98. /**
  99. * Validate the password to the defined parameters. If a parameters is not
  100. * set at runtime then a default value is used.
  101. *
  102. * @param string $password The password.
  103. *
  104. * @return boolean True if password valid, otherwise false.
  105. */
  106. public function validatePassword($password) {
  107. // Make sure that parameters don't overlap in such a way as to make
  108. // validation impossible.
  109. $this->_sanitizeInputs();
  110. $this->errors = array();
  111. // Check password minimum length, return at this step.
  112. if (strlen($password) < $this->minLength) {
  113. $this->errors[] = 'Password must be ' . $this->minLength . ' characters long, current '
  114. . 'password is too short at ' . strlen($password) . ' characters.';
  115. return false;
  116. }
  117. // Check password maximum length, return at this step.
  118. if (strlen($password) > $this->maxLength) {
  119. $this->errors[] = 'Password must be ' . $this->minLength . ' characters long, current '
  120. . 'password is too long at ' . strlen($password) . ' characters.';
  121. return false;
  122. }
  123. // Check the number of numbers in the password.
  124. if (strlen(preg_replace('/([^0-9]*)/', '', $password)) < $this->minNumbers) {
  125. $this->errors[] = 'Not enough numbers in password, a minimum of ' . $this->minNumbers . ' required.';
  126. }
  127. // Check the number of letters in the password
  128. if (strlen(preg_replace('/([^a-zA-Z]*)/', '', $password)) < $this->minLetters) {
  129. $this->errors[] = 'Not enough letters in password, a minimum of ' . $this->minLetters . ' required.';
  130. }
  131. // Check the number of lower case letters in the password
  132. if (strlen(preg_replace('/([^a-z]*)/', '', $password)) < $this->minLowerCase && $this->minLowerCase != 0) {
  133. $this->errors[] = 'Not enough lower case letters in password, a minimum of '
  134. . $this->minLowerCase . ' required.';
  135. }
  136. // Check the number of upper case letters in the password
  137. if (strlen(preg_replace('/([^A-Z]*)/', '', $password)) < $this->minUpperCase && $this->minUpperCase != 0) {
  138. $this->errors[] = 'Not enough upper case letters in password, a minimum of '
  139. . $this->minUpperCase . ' required.';
  140. }
  141. // Check the minimum number of symbols in the password.
  142. if (strlen(preg_replace('/([a-zA-Z0-9]*)/', '', $password)) < $this->minSymbols && $this->maxSymbols != 0) {
  143. $this->errors[] = 'Not enough symbols in password, a minimum of ' . $this->minSymbols . ' required.';
  144. }
  145. // Check the maximum number of symbols in the password.
  146. if (strlen(preg_replace('/([a-zA-Z0-9]*)/', '', $password)) > $this->maxSymbols) {
  147. if ($this->maxSymbols == 0) {
  148. $this->errors[] = 'You are not allowed any symbols in password, please remove them.';
  149. } else {
  150. $this->errors[] = 'Too many symbols in password.';
  151. }
  152. }
  153. // Check that the symbols present in the password are allowed.
  154. if ($this->maxSymbols != 0) {
  155. $symbols = preg_replace('/([a-zA-Z0-9]*)/', '', $password);
  156. for ($i = 0; $i < strlen($symbols); ++$i) {
  157. if (!in_array($symbols[$i], $this->allowedSymbols)) {
  158. $this->errors[] = 'Non specified symbol ' . $symbols[$i] . ' used in password, '
  159. . 'please use one of ' . implode('', $this->allowedSymbols) . '.';
  160. }
  161. }
  162. }
  163. // If any errors have been encountered then return false.
  164. if (count($this->errors) > 0) {
  165. return false;
  166. }
  167. return true;
  168. }
  169. /**
  170. * Score the password based on the level of security. This function doesn't
  171. * look at the parameters set up and simply scores based on best practices.
  172. * The function first makes sure the password is valid as there is no
  173. * point in scoring a password that can't be used.
  174. *
  175. * @param string $password The password to score.
  176. *
  177. * @return mixed Returns an integer score of the password strength.
  178. */
  179. public function scorePassword($password) {
  180. // Make sure password is valid.
  181. if (!$this->validatePassword($password)) {
  182. return 0;
  183. }
  184. if ($password == '') {
  185. $this->score = 0;
  186. return $this->score;
  187. }
  188. // Reset initial score.
  189. $this->score = 100;
  190. $passwordLetters = preg_replace('/([^a-zA-Z]*)/', '', $password);
  191. $letters = array();
  192. for ($i = 0; $i < strlen($passwordLetters); ++$i) {
  193. // Reduce score for duplicate letters.
  194. if (in_array($passwordLetters[$i], $letters)) {
  195. $this->score = $this->score - 5;
  196. }
  197. // Reduce score for duplicate letters next to each other.
  198. if (isset($passwordLetters[$i - 1]) && $passwordLetters[$i] == $passwordLetters[$i - 1]) {
  199. $this->score = $this->score - 10;
  200. }
  201. $letters[] = $passwordLetters[$i];
  202. }
  203. // Reduce score for duplicate numbers.
  204. $passwordNumbers = preg_replace('/([^0-9]*)/', '', $password);
  205. $numbers = array();
  206. for ($i = 0; $i < strlen($passwordNumbers); ++$i) {
  207. if (in_array($passwordNumbers[$i], $numbers)) {
  208. $this->score = $this->score - 5;
  209. }
  210. $numbers[] = $passwordNumbers[$i];
  211. }
  212. // Reduce score for no symbols.
  213. if (strlen(preg_replace('/([a-zA-Z0-9]*)/', '', $password)) == 0) {
  214. $this->score = $this->score - 10;
  215. }
  216. // Reduce score for words in dictionary used in password.
  217. $dictionary = dirname(__FILE__) . '/words.txt';
  218. if (file_exists($dictionary)) {
  219. $handle = fopen($dictionary, "r");
  220. $words = '';
  221. while (!feof($handle)) {
  222. $words .= fread($handle, 8192);
  223. }
  224. fclose($handle);
  225. $words = explode("\n", $words);
  226. foreach ($words as $word) {
  227. if (preg_match('/.*?' . trim($word) . '.*?/i', $password, $match)) {
  228. $this->score = $this->score - 20;
  229. }
  230. }
  231. }
  232. if ($this->score < 0) {
  233. $this->score = 0;
  234. }
  235. // Return the score.
  236. return $this->score;
  237. }
  238. /**
  239. * Use the options set up in the class to create a random password that passes
  240. * validation. This uses certain practices such as not using the letter o or
  241. * the number 0 as these can be mixed up.
  242. *
  243. * @return string The generated password.
  244. */
  245. public function generatePassword() {
  246. // Make sure that parameters don't overlap in such a way as to make
  247. // validation impossible.
  248. $this->_sanitizeInputs();
  249. // Initialise variable.
  250. $password = '';
  251. // Add lower case letters.
  252. $lowerLetters = 'aeiubdghjmnpqrstvxyz';
  253. if ($this->minLowerCase != 0) {
  254. for ($i = 0; $i < $this->minLowerCase; ++$i) {
  255. $password .= $lowerLetters[(rand() % strlen($lowerLetters))];
  256. }
  257. }
  258. // Add upper case letters.
  259. $upperLetters = 'AEUBDGHJLMNPQRSTVWXYZ';
  260. if ($this->minUpperCase != 0) {
  261. for ($i = 0; $i < $this->minUpperCase; ++$i) {
  262. $password .= $upperLetters[(rand() % strlen($upperLetters))];
  263. }
  264. }
  265. // Add letters.
  266. if (($this->minLowerCase + $this->minUpperCase) < ($this->minLetters)) {
  267. $password .= $lowerLetters[(rand() % strlen($lowerLetters))];
  268. }
  269. // Add numbers.
  270. $numbers = '23456789';
  271. if ($this->minNumbers != 0) {
  272. for ($i = 0; $i < $this->minNumbers; ++$i) {
  273. $password .= $numbers[(rand() % strlen($numbers))];
  274. }
  275. }
  276. // Add symbols using the symbols array.
  277. if ($this->maxSymbols != 0) {
  278. $symbols = implode('', $this->allowedSymbols);
  279. if ($this->minSymbols != 0 && strlen($symbols) > 0) {
  280. for ($i = 0; $i < $this->minSymbols; ++$i) {
  281. $password .= $symbols[(rand() % strlen($symbols))];
  282. }
  283. }
  284. }
  285. // If the created password isn't quite long enough then add some lowercase
  286. // letters to the password string.
  287. if (strlen($password) < $this->minLength) {
  288. while (strlen($password) < $this->minLength) {
  289. $password .= $lowerLetters[(rand() % strlen($lowerLetters))];
  290. }
  291. }
  292. // Shuffle the characters in the password.
  293. $password = str_shuffle($password);
  294. // Return the password string.
  295. return $password;
  296. }
  297. /**
  298. * Set multiple options for the object in one go.
  299. *
  300. * @param array $options An associative array of options.
  301. *
  302. * @return null
  303. */
  304. public function setOptions($options) {
  305. if (isset($options['maxLength'])) {
  306. $this->maxLength = $options['maxLength'];
  307. }
  308. if (isset($options['minLength'])) {
  309. $this->minLength = $options['minLength'];
  310. }
  311. if (isset($options['minNumbers'])) {
  312. $this->minNumbers = $options['minNumbers'];
  313. }
  314. if (isset($options['minLetters'])) {
  315. $this->minLetters = $options['minLetters'];
  316. }
  317. if (isset($options['minSymbols'])) {
  318. $this->minSymbols = $options['minSymbols'];
  319. }
  320. if (isset($options['maxSymbols'])) {
  321. $this->maxSymbols = $options['maxSymbols'];
  322. }
  323. if (isset($options['allowedSymbols'])) {
  324. if (is_array($options['allowedSymbols'])) {
  325. $this->allowedSymbols = $options['allowedSymbols'];
  326. }
  327. }
  328. if (isset($options['minLowerCase'])) {
  329. $this->minLowerCase = $options['minLowerCase'];
  330. }
  331. if (isset($options['minUpperCase'])) {
  332. $this->minUpperCase = $options['minUpperCase'];
  333. }
  334. // Make sure that parameters don't overlap in such a way as to make
  335. // validation impossible.
  336. $this->_sanitizeInputs();
  337. }
  338. /**
  339. * Get any errors produced through the last validation.
  340. *
  341. * @return array
  342. */
  343. public function getErrors() {
  344. return $this->errors;
  345. }
  346. /**
  347. * Get the maximum length of password allowed.
  348. *
  349. * @param integer $maxLength The maximum length of password allowed.
  350. *
  351. * @return null
  352. */
  353. public function setMaxLength($maxLength) {
  354. $this->maxLength = $maxLength;
  355. }
  356. /**
  357. * The maximum character length of the password.
  358. *
  359. * @return integer The maximum character length of the password.
  360. */
  361. public function getMaxLength() {
  362. return $this->maxLength;
  363. }
  364. /**
  365. * The minimum character length of the password.
  366. *
  367. * @return integer The minimum character length of the password.
  368. */
  369. public function getMinLength() {
  370. return $this->minLength;
  371. }
  372. /**
  373. * Get the minimum length of password allowed.
  374. *
  375. * @param integer $minLength The minimum length of password allowed.
  376. *
  377. * @return null
  378. */
  379. public function setMinLength($minLength) {
  380. $this->minLength = $minLength;
  381. }
  382. /**
  383. * The minimum letter count in the password.
  384. *
  385. * @return integer The minimum letter count in the password.
  386. */
  387. public function getMinLetters() {
  388. return $this->minLetters;
  389. }
  390. /**
  391. * Get the symbols allowed in password.
  392. *
  393. * @return array The allowed symbols array.
  394. */
  395. public function getAllowedSymbols() {
  396. return $this->allowedSymbols;
  397. }
  398. /**
  399. * An array of symbols that can be included in the password. If an array is
  400. * not passed to this function then it is not stored.
  401. *
  402. * @param array|string $symbols An array of symbols that can be included in the
  403. * password. This can be a string, which will be parsed
  404. * into an array of symbols.
  405. *
  406. * @return null
  407. */
  408. public function setAllowedSymbols($symbols) {
  409. if (!is_array($symbols)) {
  410. $symbols = preg_split('//', $symbols);
  411. }
  412. // Filter the symbols to remove any non symbol characters.
  413. $symbols = array_filter($symbols, array($this, 'filterAllowedSymbols'));
  414. if (is_array($symbols)) {
  415. $symbols = array_unique($symbols);
  416. $this->allowedSymbols = $symbols;
  417. }
  418. }
  419. /**
  420. * Callback function for setAllowedSymbols() to allow non symbol characters to be
  421. * filtered out of the symbols array upon insertion.
  422. *
  423. * @param mixed The array item to inspect.
  424. *
  425. * @return boolean False if the item is a symbol, otherwise true.
  426. */
  427. protected function filterAllowedSymbols($character) {
  428. if (preg_match('/[^a-zA-Z0-9 ]/', $character) == 1) {
  429. return 1;
  430. } else {
  431. return 0;
  432. }
  433. }
  434. /**
  435. * Set the minimum number of symbols required in the password.
  436. *
  437. * @param integer $minSymbols The minimum number of symbols.
  438. *
  439. * @return null
  440. */
  441. public function setMinSymbols($minSymbols) {
  442. $this->minSymbols = $minSymbols;
  443. }
  444. /**
  445. * Get the minimum number of symbols required in the password.
  446. *
  447. * @return integer The minimum number of symbols.
  448. */
  449. public function getMinSymbols() {
  450. return $this->minSymbols;
  451. }
  452. /**
  453. * Get the minimum number of upper case letters required in the password.
  454. *
  455. * @return integer The minimum number of upper case letters.
  456. */
  457. public function getMinUpperCase() {
  458. return $this->minUpperCase;
  459. }
  460. /**
  461. * Get the minimum number of lower case letters required in the password.
  462. *
  463. * @return integer The minimum number of lower case letters.
  464. */
  465. public function getMinLowerCase() {
  466. return $this->minLowerCase;
  467. }
  468. /**
  469. * Set the maximum number of symbols required in the password.
  470. *
  471. * @param integer $maxSymbols The maximum number of symbols.
  472. *
  473. * @return null
  474. */
  475. public function setMaxSymbols($maxSymbols) {
  476. $this->maxSymbols = $maxSymbols;
  477. }
  478. /**
  479. * The maximum number of symbols allowed in the password.
  480. *
  481. * @return integer The maximum number of symbols allowed in the password.
  482. */
  483. public function getMaxSymbols() {
  484. return $this->maxSymbols;
  485. }
  486. /**
  487. * Make sure that parameters don't overlap in such a way as to make
  488. * validation impossible. For example, if the minimum number of letters
  489. * numbers and symbols allowed is greater than the maximum length of the
  490. * password then these numbers are added together and used as the new maximum
  491. * password length.
  492. *
  493. * @return null
  494. */
  495. private function _sanitizeInputs() {
  496. $minPosLength = $this->minNumbers + $this->minLetters + $this->minSymbols;
  497. if ($minPosLength > $this->minLength) {
  498. $this->minLength = $minPosLength;
  499. }
  500. if ($this->minLength > $this->maxLength) {
  501. $this->minLength = $this->maxLength;
  502. }
  503. if ($this->minSymbols > $this->maxSymbols) {
  504. $this->minSymbols = $this->maxSymbols;
  505. }
  506. }
  507. }