I use contact forms on many websites, and over the years I have discovered many problems with using them, including hijacking, mail injection, server hacks, XSS and platform issues.
The main cause of this is simply due to lack of validation and error checking.
Firstly you must fully understand how forms work with PHP. When you set the form “method” to POST, it sends the data to PHP as a super global variable called “$_POST”. In the HTML each “input” has a “name”, that is used to identify the related data.
For example, there is an input field named “message”, to retrieve this in PHP you simply use “$_POST[‘message’]”, we will be using this method to pass the data between the form and PHP for processing.
This is a fine example of how NOT to do it, so what is wrong with this method you may ask?
Here are some of the issues we need to overcome:
- Data directly input into the mail() function without processing
- Does data from input fields contain malicious code
- Check user input is not empty
- Validation on user inputs
- If the email address the user entered is real
- Whether the email successfully sent or not
- Ensure the correct data is processed
- Which website the form was sent from
- The IP address of the sender
- Display the form at appropriate times
- Append additional fields to the end of the message
Download here: PHP Contact Form by HM2K v1.0.1
The comments I have made within the code explains the reason what it does, and why it is included.
I hope this solves some of the problems people experience with contact forms.