Last active
December 8, 2022 06:27
-
-
Save NickSdot/c18e07a933cae9db8027e63cca4a182e to your computer and use it in GitHub Desktop.
This PHP class allows you to generate safe passwords with a length between 16-20 characters. The passwords generated by this class will pass the Laravel `Rules/Password::default() check`, making them suitable for suggesting strong and secure passwords to users. To generate and return a password, simply call: `PasswordString::make()`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Base; | |
class PasswordString | |
{ | |
const LEGAL_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*[]{}()_+-=,.<>?;:|'; | |
public static function make(): string | |
{ | |
preg_match('/[a-z]+/', static::LEGAL_CHARS, $lowerCaseMatches); | |
preg_match('/[A-Z]+/', static::LEGAL_CHARS, $upperCaseMatches); | |
preg_match('/[0-9]+/', static::LEGAL_CHARS, $numberMatches); | |
preg_match('/[!@#$%^&*]+/', static::LEGAL_CHARS, $specialMatches); | |
$requiredChars = [ | |
self::getRandomCharFrom($upperCaseMatches[0]), | |
self::getRandomCharFrom($lowerCaseMatches[0]), | |
self::getRandomCharFrom($numberMatches[0]), | |
self::getRandomCharFrom($specialMatches[0]), | |
self::getRandomCharFrom(static::LEGAL_CHARS, rand(12, 16)), | |
]; | |
return str_shuffle(implode("", $requiredChars)); | |
} | |
private static function getRandomCharFrom(string $string, int $quantity = 1): string | |
{ | |
return substr(str_shuffle($string), 0, $quantity); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment