Create Preg_Match for Password Validation Allowing (!@#$%)

Create preg_match for password validation allowing (!@#$%)

I think this should look like that:

if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
echo 'the password does not meet the requirements!';
}

Between start -> ^
And end -> $
of the string there has to be at least one number -> (?=.*\d)
and at least one letter -> (?=.*[A-Za-z])
and it has to be a number, a letter or one of the following: !@#$% -> [0-9A-Za-z!@#$%]
and there have to be 8-12 characters -> {8,12}

As user557846 commented to your question, I would also suggest you to allow more characters, I usually (if i use a maximum) take at least 50 :)

btw, you might want to take a look at this regex tutorial

Password parameters using preg_match

Don't do it all with one regex. It will be far more maintainable, understandable, and easier to change in the future if you make multiple calls to preg_match with multiple regexes.

$password_is_ok =
preg_match( '/\W/', $pass ) &&
preg_match( '/\d/', $pass ) &&
preg_match( '/[a-z]/', $pass ) &&
preg_match( '/[A-Z]/', $pass ) &&
strlen( $pass ) >= 8 &&
strlen( $pass ) <= 20;

That is far more readable and understandable by the next person who has to read your code (who might be you) than any single-regex monstrosity you can concoct.

Using preg_match to identify a strong password

PHP regex needs regex delimiters also, so use:

$pattern = '/(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/';

validate password with preg_match in php

Imposing arbitrary complexity rules on passwords is very user hostile and does not improve security substantially. Don't do it.

Here's why I think the above statement is true:

  • If I want to use your website with "123456" as my password, it's my problem. Let me roll with it.
  • You may impose a minimum length (e.g. 6 characters), but not a maximum. If I want to cite the entire John Maynard as my password, let me roll with it.
  • Your idea of a "secure" password might not be everybody else's idea.
  • People might use password generators that do not automatically comply with your rule set. Don't annoy them by not accepting their password for no other reason than not containing enough/or too many "special characters".
  • You must hash your customer's passwords with a decent hashing algorithm plus a random hash salt, different for every user. Only store hash salts and hashes in the database, never store clear text passwords.
  • Once hashed, even a lame password is reasonably secure against theft/cracking. Implement security against brute-force attacks (time-based lock-outs, IP-based lock-outs, password locking with e-mail handshake to retrieve a locked account).

So your password validation process goes like this

  • New user? Create user record with username and random salt (never change the salt value for that user)
  • Returning user? Fetch salt from DB, re-hash his password, compare result to hash in DB.
  • Never store the user's password anywhere physically and use HTTPS to transmit it.
  • If you do not want to do something like the above, think about using OAuth with your site. May not be easy either, but you do not have to worry about password security anymore and your users have one less password to remember.

For the sake of the argument, this regex will do what you ask. If you're still desperate to do it.

preg_match("/^[a-z0-9_-]{6,40}$/i", $pass)

password checking function with preg_match

The dash/minus character is your issue, as when inside a character group, it denotes a character range.

You need to either:

  • Escape it with a backslash, so that it isn't treated as a special character:

    /[!@#$%^&*()\-+<>]+/
  • Or put it at the end of the pattern, so the PCRE engine knows it can't possibly denote a range:

    /[!@#$%^&*()+<>-]+/

Similarly, the caret (^) is also a special character, denoting negation when inside a character group, but because you didn't put it at the very first position inside the character group, the PCRE engine knows it has no special meaning in your case.

PHP regex for password validation

Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>

^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$

Add your special character set to last [...] in the above regex (I put there for now just -+%#).


Explanation:

^                              - beginning of line/string
(?=.{8}) - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z]) - ...to ensure we have at least one uppercase char
(?=.*[a-z]) - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])
- ...to ensure we have at least three special chars
(characters other than letters and numbers)
[-+%#a-zA-Z\d]+ - combination of allowed characters
$ - end of line/string

Regex for password PHP

One possible regex pattern is:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/

As in this example.

But you really shouldn't limit passwords!

Sample Image

Admit it. As a developer we have done more to contribute to the failure of our customer's and user's online security because we are too stubborn or lazy to handle passwords properly. Just look at some of the fruit of our labor:

Password must be between 5 and 32 characters in length. Valid characters include letters, numbers, and underscore.

Password must be between 6 and 12 characters in length. Valid characters include letters and numbers.

Password must be a minimum of 8 characters and contain at least one capital letter, a number and a special character such as an underscore or exclamation point.

Then there is this gem. The original requirements were a minimum of 8 characters. Accidentally putting in 7 characters causes an error to appear before the user:

Sample Image

Password Limitation Gone Wrong
Note the tag line. Irony?

I could go on here, but I think you get the point. We have written code to support this nonsense, wrapping our heads around the right regex to account for every case. Agonizing over transmission, hashing and storage. We've talked about this so much the situation has even received proper pop culture status with its memorialization on xkcd.

There is no doubt our intentions were good. After all, users and customers cannot be expected to protect themselves properly. They don't create strong passwords, they use the word 'password' as their password more often than not. They don't heed the warnings, the news stories or the horror exrpressed by friends who have suffered through identity theft. The hacking of large retail chains phases them very little. We, as developers, set out to help our users avoid these pitfalls. I will alledge our attempts fell short and may have even contributed to the problem.

Very likely we've made it worse.

By placing arcane restrictions on passwords we have actually forced our users into a bad way of thinking and therefore made them seek the path of least resistance, simple, hackable passwords. We did this because we were used to restrictions on us. Sysadmins limited us to 8 characters so we projected the limit on to the rest of the world. It is time we stopped and learned how to handle any length of password with any character included. We may want to exclude white spaces from the password, but other than that we shouldn't place any restrictions on passwords.

Then we can encourage good security practices like passphrases or random words. Users, once they discover this, will be blissfully happy they don't have to remember some goofy combination of letters and numbers like f@rtp00p.

I can see you rolling your eyes. It means you have to learn how to properly hash passwords and how to compare entered passwords with the hashes. You'll have to toss some really hard won regex. Heaven forbid you might have to refactor some code! Databases can hold very large hashed passwords and we should take advantage of the capability.

Keep in mind the general security of the data is on me, the developer along with the sysadmin and others. The security of a user's account is on them and I shouldn't do anything to hold them back. Personally I do not care what my users have for their passwords. All I do when users create their passwords is provide a strength meter and some basic guidelines:

"We have found using passphrases or multiple word combinations to be the most secure when it comes to preventing a hacker, who is trying to crack your login information, from being successful."

What should you do?

PHP's built-in functions handle password security perfectly, spaces, special characters and all.. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack.

We need to remove the limitations on passwords and free up the users to own their security online. Are you in?



Related Topics



Leave a reply



Submit