views:

146

answers:

3

Hi. I am working on validating username, pass and email with php. I need to be sure I get it right so nobody can bypass the login page.

This is the values:

$email=$_POST['email'];
$username=$_POST['uname'];
$passwd=$_POST['pass'];
$passwd2=$_POST['passcopy'];

So far I have email validation:

if(!(preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
    die(msg(0,"You haven't provided a valid email"));

password equal:

if ($passwd != $passwd2) {
die(msg(0,"Passwords are not equal"));
}

password length:

if ((strlen($passwd) < 8) || (strlen($passwd) > 16)) {
die(msg(0,"Your password must be between 8 and 16 characters. Please type in a longer password"));
}

I know I need to validate the username. I was thinking only lowercase a-z0-9 to avoid people making similar usernames? Then password, what characters should I allow in a password?

PS. I still don't understand preg_match and ereg. If somebody could explain this "/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+ and make a preg_match for my username and password validation it would be very helpful.

+1  A: 

the string "^[.A-z0-9_-+]+[@][A-z0-9_-]+" is a regular expression, that describes a pattern that you validate the email string against.

Let me break the different parts down for you.

^ this indicates that the pattern should start matching at the beginning of the line.

[.A-z0-9_-+]+ this part is composed of two sub parts, first [.A-z0-9_-+] that describes a class of characters, and then a + that indicates that you want one or more of the previous class.

[@] matches exactly one @ sign.

[A-z0-9_-]+ another class of characters with a + after that means that you want one or more of the characters that are in the class.

Alexander Kjäll
A: 

PS. I still don't understand preg_match and ereg. If somebody could explain this

It's a very bad example of how to check for a valid email address. Try google for better examples. Note that just because it matches a good regex does not mean that the person is receiving mail there - a far better approach if you need to validate an email address is to mail an activation URL or an initial password to the supplied address.

make a preg_match for my username and password validation

erm, a lesson in regexes would take rather a long time - try this

It really doesn't matter what the username (or password) contains as long as the combination is unique and you handle the data properly

C.

symcbean
A: 

preg_match and ereg are two ways of matching a string via a regular expression. The preg functions use the PCRE (perl-compatible regular expression) engine and are the recommended regular expression functions for php; the ereg functions are deprecated now.

I won't go through explaining the pattern because it's covered in other answers, but if you want a really thorough regular expression tutorial (and free, to boot), check out the tutorial on regular-expressions.info.

Daniel Vandersluis