Reputation: 24995
Is there a native PHP function for rejecting invalid $_POST data from simple text fields?
Currently I'm using custom filter functions with regular expressions, and would really like to simplify my code if possible.
For example, let's say I have a form field for entering a last name. I want to check the submitted value and immediately reject the input if it contains any invalid characters.
Here are my criteria for considering PHP functions:
A person's last name might be "Smith-Johnson", "Van Buren", "O'Malley", etc., so the function needs to tolerate spaces, hyphens, apostrophes, etc.
My goal is to test the input and reject it right away -- as opposed to sanitizing it and running it through additional filters and processing steps.
Two examples of input that I want to catch are:
username' --
username; DELETE FROM users;
Here are the options I'm aware of and why I have doubts about using them...
is_string(): This function doesn't seem to catch either of the two examples above
addslashes(): This function fails the second criterion
htmlentities(), htmlspecialchars(): Same as addslashes(); if input is invalid, I don't want to keep working with it, even if it's sanitized
strip_tags(): Fails the second criterion, but preferred over #3 because it eliminates unwanted characters rather than sanitizing them
filter_input(...FILTER_SANITIZE_STRING): As far as I can tell, this is identical to strip_tags(). **
ctype_alpha(), ctype_alnum(): Fails the first criteria because it doesn't allow spaces and other characters.
Regex/Custom Functions: This is what I've been using. I'd really prefer to simplify my code and eliminate the (albeit minimal) regex overhead.
--
** Just curious: does PECL make filter_input() faster than strip_tags()?
Upvotes: 0
Views: 316
Reputation: 1984
There is no such function. You're asking basically how to tell one string from another one while they're both strings with complex criteria. That's quite a vague task for a "native" function.
The most "native" way of achieving that is to use regular expressions, and that's what you're already doing.
It is also against the ideology as $_POST and $_GET are supposed to represent parameters in their raw form, not after passing some validation.
Upvotes: 1
Reputation: 3028
I always use regular expressions to validate form input. I have a whole suite of form validation and creation functions that I have developed over the years if you are interested.
Upvotes: 0