Search code examples
phphtmlvalidationsecurityhtmlspecialchars

Input-validation for free text fields


I searched a lot about form-validation in PHP. Unfortunately all tutorials about the validation mechanism are about specific fields like names, mails or dates. To check if the user-input in these fields are okay is simple with regex. But what is the best way to check free fields like a contact-us texteara or a comment field? Specifically in a comment field the user should also use "dangerous" chars like "<", ">" or " ' ".

What is the best way to handle the user input? Logically it's a bad idea to store the user data pure in a database. But it's also a bad idea to block characters like "<", ">" or " ' ".

I saw a function called htmlspecialchars() in PHP. A lot of websites say it's sufficient to call this function with the user input. In my eyes this solution is really risky without more checks.

Does anyone have any tips for me how I can securely validate my user input without reducing the "usability"? Thanks.


Solution

  • But what is the best way to check free fields like a contact-us texteara or a comment field? Specifically in a comment field the user should also use "dangerous" chars like "<", ">" or " ' ".

    You can use if (strpos($string, '<') !== false) for every dangerous character (where "dangerous" is very domain-specific).

    What is the best way to handle the user input? Logically it's a bad idea to store the user data pure in a database. But it's also a bad idea to block characters like "<", ">" or " ' ".

    1. For preventing SQL injection, just use prepared statements. (Caveat: Not emulated prepared statements.)
    2. For preventing XSS, escape on output, never on input.

    There is no magical panacea for input validation. You have to know what your code is doing with the data to determine what's safe and what's unsafe. LDAP queries have different security requirements than SQL queries, XPath queries, or filesystem paths.

    If you're looking for a more general input validation library for reasons outside security, Ionizer is worth checking out.