I Made a PIN authentication on my website, and I don’t want my user using common PINs like 12345, 11111, 121212, etc.
I tried this
if($PIN=="111111" || $PIN="222222"){ echo "This PIN is common"; }
But I think that Will be too long for a simple function? How to simplify it?
Advertisement
Answer
Your problem is actually quite simple, you want, for example, to avoid pins that have multiples iterations of a same character in a row OR/AND avoid pins that have a same character repeated more than X times in a string.
Using Regex we can easily achieve something like this: For example, the following will return 1 if 3 characters or more are in a row.
<?php $pin = '111025'; if ( preg_match( '/(.)1{2}/', $pin ) ) { return true; } else { return false; }; ?>
Learn more
RegEx
.
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
Function | Description |
---|---|
preg_match() |
Returns 1 if the pattern was found in the string and 0 if not |
( ) |
You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match |
. |
Find just one instance of any character |
n{x} |
Matches any string that contains a sequence of X n’s |
PHP RegEx
@ https://www.w3schools.com/php/php_regex.asp