cantera
cantera

Reputation: 24995

PHP Native Function to Filter Common Text Fields

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:

Here are the options I'm aware of and why I have doubts about using them...

  1. is_string(): This function doesn't seem to catch either of the two examples above

  2. addslashes(): This function fails the second criterion

  3. htmlentities(), htmlspecialchars(): Same as addslashes(); if input is invalid, I don't want to keep working with it, even if it's sanitized

  4. strip_tags(): Fails the second criterion, but preferred over #3 because it eliminates unwanted characters rather than sanitizing them

  5. filter_input(...FILTER_SANITIZE_STRING): As far as I can tell, this is identical to strip_tags(). **

  6. ctype_alpha(), ctype_alnum(): Fails the first criteria because it doesn't allow spaces and other characters.

  7. 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

Answers (2)

Yuriy
Yuriy

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

Knyri
Knyri

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

Related Questions