Vladimir Vladimir - 9 months ago 59
PHP Question

Safe way to get alpha-numeric string from user input? (without preg_replace)

I have read many other questions regarding how to filter a string to "Alpha-numeric", but all of them suggest the


According to OWASP:

Function preg_replace() should not be used with unsanitised user
input, because the payload will be eval()’ed13.

preg_replace("/.*/e","system(’echo /etc/passwd’)");

Reflection also could
have code injection flaws. Refer to the appropriate reflection
documentations, since it is an advanced topic.

So now how do I achieve this without preg_replace?

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $_POST['data']);
// Notice the $_POST['data']

Answer Source

There's no problem using preg_replace() to filter user inputs. The OWASP advice you've quoted is talking about the pattern not being user input itself.

However, I'd say that using filtered inputs is a problem by itself - you should validate instead. As in, don't accept invalid inputs.