I was wondering that, if preg_match() could be used as the only line of defense on PHP.
Testing preg_match(), at least for a simple input form field, it accepts only what's acceptable by regex and returns false for everything else:
For numbers:
function GetUserID($userid) {
$regexnum = "/^[0-9]+$/";
if(preg_match($regexnum, $userid) != 1 OR empty($userid)) {
return false;
}
else {
return $userid;
}
}
For names:
function GetUsername ($user) {
$regex = "/^[a-zA-Zà-ûÀ-ÛçÇ\s]+$/";
if (preg_match($regex, $user) != 1 OR empty($user)) {
return false;
}
else {
return $user;
}
}
So my question is, can preg_match() be the only line of defense without using htmlentities() or filter_var() as it doesn't accept anything alse or am I missing something?
* Edit * I've created this code to test it: Test Site
Yes. However it's a good idea to not rely on it exclusively, because a slight change to the regex could make you vulnerable. Using the proper escaping function is ideal because even if your validation code changes, your sanitisation code will not.