Securing PHP Web Forms

Chris Coyier has written an interesting article on securing form scripts. Serious Form Security talks about token matching, hack logging, and a few other useful techniques to apply to a form processing script. Token matching is definitely a trick worth learning, since it will do a lot to stop bots from submitting data through your form.

The first thing that we are going to do is generate a “token”, essentially a secret code. This token is going to be part of our “session”, meaning it is stored server side. This token also is going to be applied as a hidden input on the form itself when it is first generated in the browser. That means this token exists both on the client side and the server side and we can match them when the form gets submitted and make sure they are the same.

One of the best (worst?) ways to spam forms is to create a script that uses cURL to send POST requests to the URL listed in the form’s action attribute, with some spammy data in the POST fields. (Or malicious data intended to break your script…) By having a pseudo-random token generated like the article describes, it makes things a lot harder. cURL, whether from a command line or an automated script, isn’t going to be able to store the session data and send the token along with the form.