Contact Page
In this step we will incorporate server-side input validation into the form on the contact page.
Here's the algorithm we'll follow:
- Get the data entered by the user (from the $_POST super-global array)
-
If the data is valid:
- Send an email to the site adminstrator with the data.
- Redirect to a page that confirms to the user that the contact information has been sent.
-
If the data is NOT valid:
-
Send an email to the site admin notifying of a security issue
(if the data is not valid, then the JavaScript validation code has been bypassed)!!!!!
To complete this task, follow these steps:
- Open the contact page in your editor.
-
Add this code to the PHP code at the top of the contact page,
just after the $sideBar variable and before the line that links to the header.inc.php file
Note that there is a function being called that we have not yet defined.
We'll define validateContactData() at the bottom of the contact page next.
Finally, note that after sending the contact details in an email, we use the PHP header() function to redirect to a page that will tell the user that we received the information.
We'll create that page in a moment.
-
Add this PHP code for the validateContactData() function, put the code just under the link to the footer.inc.php file.
Note that validateContactData() returns true if the user input is valid.
If it returns false, then we suspect that there has been some sort of foul play becuase the client-side code (JavaScript validation code) should have prevented the user from entering invalid data.
So it's likely that a spam bot is sending POST requests to this page and bypassing the client-side validation.
Beware that you are likely to get quite a few security warning emails.
We'll work on preventing spam emails later.
But for now, whenever you suspect foul play, you want to capture as much data as you can about the nature of the request.
That's why we defined getAllSuperGlobals() in the config file (in the previous step).
-
Create a page named contact-confirmation.php and put it in the my-new-site folder.
You can copy code from the home page and then make the appropriate updates, just as we did when we created error.php.
-
Test the site on your dev and live server.
You may run into problems on the dev server (in XAMPP) because it's not configured to send emails.
Update to the sendEmail() function
I went back and made some changes to the sendEmail() function (in the config file):
-
I updated code in sendEmail to allow html emails, and to allow you attach various headers to the emails that are sent.
-
Here's sendEmail().
Seems weird how you have to use single and double quotes when concatenating the string, but that's how it works.
You can read more about about sending emails from PHP in your book!
-
Here's the change to contact.php (notice the last param on line 22)