Php script for validating forms
The important characteristics of a form handler is that it verifies that the required variables have been set, and that they have appropriate values.Remember to be thorough as this is your last (only real) line of defence against malicious scripts. Naming the button is useful in case there are multiple forms on the page. In reality we have special functions for validating email addresses and other data types - as will most Java Script libraries.The PHP code needs to appear at the top of the page - before any HTML or whitespace is displayed.It prevents the form from being resubmitted if the landing page is reloaded, and allows us to display validation error messages inline using PHP.Finally, the code includes PHP commands to re-insert any submitted values back in to the form so they don't have to be retyped in case of an error.If errors are found in the submission, the form is cancelled and a list of errors is displayed at the top of the form.
The first thing the form handler does is check that all the fields in our form, including the button, appear in the POST array. We also have more advanced functions for sending email.
For public-facing forms you should add a CAPTCHA or similar device, as you can see in our Feedback form below, or risk being bombarded by spambots.