How would you check for illegal letters from form field?
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...
It depends on what you wish to consider illegal. ctype_alnum() checks for only alphanumeric characters. If you want limited acceptance of other characters, you can use regular expressions.
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.
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
PHP Code:
if (preg_match('/^[a-z0-9]{4,10}$/i', $username)) {
// Ok
} else {
// Not ok
}
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 +).
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?
if (strlen($username) >= 4 && strlen($username) <= 16) { // Username is Ok and within the requested length } // Username is Ok, but NOT within the requested length }