...

View Full Version : How would you check for illegal letters from form field?



kaisellgren
06-16-2006, 10:53 PM
Hi,

If user is asked for a username and password in a form. How would you do a check in PHP to make sure that username and password has no illegal characters such as, new line, tab, / or \, *, -, ., ,,, ", ', so on...

Kid Charming
06-16-2006, 11:10 PM
It depends on what you wish to consider illegal. ctype_alnum() (http://us3.php.net/manual/en/function.ctype-alnum.php) checks for only alphanumeric characters. If you want limited acceptance of other characters, you can use regular expressions.

Nicklas
06-17-2006, 01:06 AM
use regular expressions. The example below, only accepts a-z and numbers, all other chars are invalid.

ex

if (preg_match('/^[a-z0-9]$/i', $username)) {
// Ok
} else {
// Not ok
}

marek_mar
06-17-2006, 01:30 AM
That regex will only match single character input.

Kid Charming
06-17-2006, 01:36 AM
Regular expressions are relatively resource intensive. Generally speaking, if you can do something without using regex, you should. If you want your users to just use letters, use ctype_alpha(). If you only want letters and numbers, use ctype_alnum(). If you want letters, numbers, and a few select extra characters, such as underscores, dollar signs, etc., then you'll need to use a regex.

Nicklas
06-17-2006, 01:41 AM
Oops, missed a + char


if (preg_match('/^[a-z0-9]+$/i', $username)) {
// Ok
} else {
// Not ok
}

If you wanna limit the length of the $username and make sure it's, for example, at least 4 chars and not longer than 10 chars, then replace the + with {minimum, maximum}

ex

if (preg_match('/^[a-z0-9]{4,10}$/i', $username)) {
// Ok
} else {
// Not ok
}

felgall
06-17-2006, 02:04 AM
preg_match('/^[a-z0-9]+$/i', $username)

and

ctype_alnum($username)

do exactly the same thing except that the second one runs a lot faster since it runs compiled code instead of interpreted script. It also avoids the possibility of a typo (such as leaving out the +).

kaisellgren
06-17-2006, 11:30 AM
Okay. I'm little confused about which one to use, preg_match or ctype_alnum... I just want that user can ONLY put a,b,c,d,...,z and 0,1,2,3,4,5,6,7,8,9 nothing else. If user types any other characters, then the code will do exit;

Yeah. A minimum 4 characters would be good and some like max 16 characters...

Well, if ctype_alnum is faster than preg_match, can I check for the lenght of the input with ctype_alnum expression?

Thanks for help!

Nicklas
06-17-2006, 03:45 PM
Something like this...

if (ctype_alnum($username)) {

if (strlen($username) >= 4 && strlen($username) <= 16) {
// Username is Ok and within the requested length
}
// Username is Ok, but NOT within the requested length
}

} else {
// Bad username!!!
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum