Handling Form Input Securely

I know this is a monster topic, but I am trying to get a handle on it from the beginning. I know about PHP’s htmlspecialchars function from Kevin Yank’s book, but I am assuming that there is a lot more to it than this. I want to secure some pre-existing forms, and I don’t mind re-writing them from scratch to do so, but I am not quite of where to begin. The data is saved in a MySQL database, so I know I have to worry about SQL injection attacks, and while I understand the basic concept, these are also a bit of a mystery to me. I am trying to learn not only the hows but the whys, so code snippets have been helpful to me only insofar as I understand their purpose (and assuming I can gather what the code does, which isn’t always the case.)

Can you please suggest some resources for learning how to secure one’s forms? Suggestions to build upon htmlspecialchars would also be appreciated.

(In case you didn’t gather - my webmaster experience is low.)

Thanks.

There are quite a few resourses gathered and pinned on this and related topics in “Web Security” subsection of this forum. Just follow link in my signature.

I’d probably begin with OWASP https://www.owasp.org/index.php/Category:Principle but anyway - see for yourself which suit you best.

Security (escaping/encoding anyway) is always in the context of where the data is going.

So you use [fphp]mysql_real_escape_string[/fphp] before using the values in a query going to MySQL. This ensures the values don’t break out of their containers and change the behaviour of the query.

When the data is going into HTML you encode with [fphp]htmlentities[/fphp] (or specialchars).

If the data will be used in mail headers you need to filter against new lines and other commands that can be used to hijack forms. It all depends on the context.

There’s also validating the data to make sure it is in the format you want. (e.g. 2391 is not a valid email address)

So to improve your current forms:

  • use trim()
  • use mysql_real_escape_string on values that will be stored as a string in the DB
  • cast to (int) or (float) for those numeric types
  • if a value is coming from a select box, check that it matches one of the allowed values you expect

htmlentities or htmlspecialchars (the former escapes a wider range of characters) comes into play when you are pulling that data out of the database and want to display it.