0

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

William
  • 1,010
  • 3
  • 21
  • 39
  • Depends on what you're doing. If you're taking real names you'd need to accept `'` and some other non-alpha characters, at which point, if used in a certain order, SQL injection could be possible. **Kids, always use proper protection!** :p – MDEV Mar 27 '14 at 16:02
  • @SmokeyPHP In Brazil we don't use `'` so on my code it accepts the common characters `á,é,ç` and some others that might come. And if there is some uncommon char the person might know that his/her name is unusual. The code on `edit` checks some random characters and didn't accept malicious code. – William Mar 27 '14 at 16:11
  • @SmokeyPHP but that's a good idea to think about inserting `'` on it. – William Mar 27 '14 at 16:16

1 Answers1

0

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Do you mean the change of `$regex`? Would that be changed only by me or by someone else with XSS or similar? – William Mar 27 '14 at 16:14
  • You might change it if you decide you want to allow apostrophes. Or another developer might do it if someone else works on your project. – Niet the Dark Absol Mar 27 '14 at 16:15