Master the basics of PHP and MySQL with our comprehensive tutorial that covers sanitizing input, error checking, displaying errors, sending email, adding a thank you page, and including files, coupled with practical exercises for a hands-on learning experience.
This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this PHP & MySQL tutorial:
Sanitizing input, Error checking, Displaying errors, Sending email, Adding a thank you page, Including files
Exercise Overview
When dealing with user input it is vital that we error-check that input and display any errors to the user. You’ve seen it many times before in any form you’ve filled out: perhaps you’ve forgotten to enter your phone number, or you got your password wrong, etc. There are two ways of doing this error checking: on the client-side and on the server-side. While it is best practice to always do both, having at least server-side is critical. Client-side validation typically uses JavaScript or a JavaScript library such as jQuery, but it cannot be relied on because a small percentage of users will have JavaScript turned off or unavailable, or worse yet a hacker may be trying to inject faulty information to your system and will purposefully bypass your client-side security.
This exercise will focus on a very simple form validation script that checks for simple errors, sanitizes input, and sends an email. There are many solutions to this common problem, but here we’ll focus on the basics so you can understand how the more robust systems are put together and perhaps adapt them to your own projects.
Getting Started
Open form.php from the form-validate-simple folder in the phpclass folder.
-
In a browser go to:
- Mac: localhost:8888/phpclass/form-validate-simple/form.php
- Windows: localhost/phpclass/form-validate-simple/form.php
We have a very simple form consisting of name, email, and checkboxes for publications that they read.
Here’s what we’ll do with the form:
- Make the name and email required.
- Make sure that the email is valid.
- Sanitize the inputs.
- Display errors if there are any.
- Send an email.
- Display a confirmation page when the email is sent.
First we need to add brackets to the publications input because PHP needs to see it as an array.
Switch back to your code editor.
-
Find the What do you read? checkbox fields around line 25. Add brackets to the name as shown in bold below:
<label><input name="publications[]" type="checkbox" id="publications_drf" value="Daily Racing Form"> Daily Racing Form</label> <label><input name="publications[]" type="checkbox" id="publications_elle" value="Elle"> Elle</label>
-
Now let’s set an action page. Around line 13 set action to form-action.php as shown in bold below:
<form action="form-action.php" method="post" name="signup" id="signup">
Save the page.
Create a new page called form-action.php and save it into the form-validate-simple folder in the phpclass folder.
Making a sanitizeInput() Function
We’re going to make a sanitizeInput()
function like before, except we are going to strip out HTML tags instead of just escaping them.
-
In form-action.php, add the following code to the page:
<?php function sanitizeInput() { } ?>
This is an empty function called
sanitizeInput()
. -
Let’s make it accept a variable called
$myInput
. Add the following bold code:function sanitizeInput($myInput) { $myInput = trim($myInput); $myInput = strip_tags($myInput); return $myInput; }
This takes $myInput and:
- Uses the
trim()
function to trim any extra whitespace. - Uses the
strip_tags()
function to strip out any HTML tags. -
Returns the modified
$myInput
variable.
- Uses the
-
Set a new empty array called
$errors
. If there are any errors on the page we can put them in there. This also makes it easy to check if the page has errors or not. If the array is empty then we can send out our email. Below thesanitizeInput()
function add the following bold code:function sanitizeInput($myInput) { $myInput = trim($myInput); $myInput = strip_tags($myInput); return $myInput; } $errors = array();
-
Add the following bold code:
$errors = array(); $name = sanitizeInput($_POST['name']); $email = sanitizeInput($_POST['email']);
This sanitizes the name and email inputs, and puts them into new variables that will make it easy to build the mail() script later.
-
That works fine for the text inputs, but the checkbox fields may or may not be returned. Because of this we will first see if
$_POST['publications']
has been set. If it was set we’llimplode()
it, then sanitize the string. To start, add the following bold code:$name = sanitizeInput($_POST['name']); $email = sanitizeInput($_POST['email']); if ( isset($_POST['publications']) ) { }
-
Add the following bold code:
if ( isset($_POST['publications']) ) { $publications = sanitizeInput( implode(', ',$_POST['publications']) ); }
This sets a new variable called $publications, uses
implode()
to turn the array into a comma-delimited list, then runs thesanitizeInput()
function. -
If
$_POST['publications']
has not been set (the user didn’t choose any checkbox) then we simply set $publication to be an empty string. Add the following bold code:if ( isset($_POST['publications']) ) { $publications = sanitizeInput( implode(', ',$_POST['publications']) ); } else { $publications = ''; }
Error Checking
Now that all the form fields have been sanitized and assigned to variables, we can get to the error checking.
-
The first thing to do is make sure that users enter a name. If they didn’t we’ll add an error to the $error array. Below the if/else statement you just entered, add the following bold code:
if ( $name == '' ) { $errors[] = "You must enter a name."; }
-
The same can be done for the email input. Add the following bold code:
if ( $email == '' ) { $errors[] = "You must enter an email."; }
It is vital that the user enters a valid email. This is a common problem and luckily there is a common solution. PHP 5 includes the
filter_var()
function which can both sanitize and validate a wide range of objects, including email addresses, URLs, integers, and more. For a complete list of filter options, see the PHP manual: php.net/manual/en/filter.filters.phpfilter_var()
takes two parameters: the first is the data to check, and the second is the type of check to run. To validate an email it would be formatted as such:filter_var($email, FILTER_VALIDATE_EMAIL)
filter_var()
returns true if it is valid, and false if it is not. Note that it is a basic formatting check (makes sure there is an @ sign, etc.) and doesn’t actually ping the mail server to see if the address exists. -
If the user did enter an email we’ll want to check if it is valid. Add the following bold code:
if ( $email == '' ) { $errors[] = "You must enter an email."; } elseif ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) { $errors[] = "That email is not valid."; }
Displaying Errors
If there are errors we need to display them to the user. We’ve already made a simple error page for you and all we need to do is loop through the $errors array and output the errors.
-
Add the following bold code:
elseif ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) { $errors[] = "That email is not valid."; } if ( empty($errors) ) { //send email and display confirm page } else { //display errors }
This says if the $errors array is empty, send the email and display a thank you page. If it is NOT empty, display the errors.
-
We’ve made a page called form-error.php that will display errors to the user. We can include it in our script for if there is an error. Replace the //display errors comment with the following bold code:
if ( empty($errors) ) { //send email and display confirm page } else { require_once('form-error.php'); }
The
require_once()
function includes a file into our script. You can think of it like PHP copying and pasting that code for us. This can be very useful if you have a bit of script that you’ll use over and over in different parts of your application.We could have also used the
include()
function, butrequire_once()
provides the following benefits:- Only includes a file a single time, in the event the statement gets called more than once in a single request
- Errors out if the file cannot be found, making it easier to debug if the path is wrong
Save the page.
Open form-error.php from the form-validate-simple folder in the phpclass folder.
-
Around line 15 find the Display errors here comment and replace it with the following bold code:
<?php foreach($errors as $value) { echo '<li>'; echo $value; echo '</li>'; } ?>
This wraps each error in an
<li>
tag (notice that the PHP code is already in an unordered list). -
Save the page and then in a browser go to:
- Mac: localhost:8888/phpclass/form-validate-simple/form.php
- Windows: localhost/phpclass/form-validate-simple/form.php
Try leaving the name blank, or entering an incorrect email. Your errors should be correctly displayed!
Sending the Email
Switch back to your code editor.
Switch to form-action.php.
-
Replace the //send email and display confirm page comment with an include as shown in bold:
if ( empty($errors) ) { require_once('form-send-email.php'); } else { require_once('form-error.php'); }
Save the page.
Create a new page called form-send-email.php and save it in the form-validate-simple folder in the phpclass folder.
-
Add the following bold code to the new page (replacing youremail@gmail.com with your actual email address if on Mac):
- Mac:
<?php $to = "youremail@gmail.com"; ?>
- Windows:
<?php $to = "newuser@localhost"; ?>
-
Continue to build up the email:
<?php $to = "youremail@gmail.com"; $subject = "You have new mail!"; $message = "You have a new signup!\r\n\r\n"; $headers = "From:newuser@localhost\r\n"; mail($to, $subject, $message, $headers); ?>
The above code builds up a simple email and sends it out.
-
Save the page and then in a browser go to:
- Mac: localhost:8888/phpclass/form-validate-simple/form.php
- Windows: localhost/phpclass/form-validate-simple/form.php
-
Fill out and submit the form, and then check your email:
- Mac: Log into your email account and enjoy your new message! If you don’t see it, check your spam folders.
- Windows: Switch to Thunderbird and click Get Mail. You’ll see your email appear.
Looking good so far; all we need to do is add the form information to the email.
Switch back to your code editor.
Make sure you are in form-send-email.php.
-
Add the following bold code:
<?php $to = "youremail@gmail.com"; $subject = "You have new mail!"; $message = "You have a new signup!\r\n\r\n"; $message .= "Name: $name \r\n"; $message .= "Email: $email \r\n"; $message .= "Publications: $publications\r\n"; $headers = "From:newuser@localhost\r\n"; mail($to, $subject, $message, $headers); ?>
The .= concatenates a string to the $message variable. The
\r\n
adds a line break to the email. -
Save the page and then in a browser go to:
- Mac: localhost:8888/phpclass/form-validate-simple/form.php
- Windows: localhost/phpclass/form-validate-simple/form.php
Try out the form again, then check your email. You’ll see all the form data is now being sent in the email!
Adding a Thank You Page
It would be nice for users to see a thank you page when they have correctly filled out the form, instead of the blank page they see now.
Switch back to your code editor.
Switch to form-action.php.
-
Find the
require_once('form-send-email.php')
and right below it add the following bold code:if ( empty($errors) ) { require_once('form-send-email.php'); require_once('form-confirm.html'); } else { require_once('form-error.php'); }
We’ve already made the form-confirm.html page so you don’t need to do anything else.
-
Save the page and then in a browser go to:
- Mac: localhost:8888/phpclass/form-validate-simple/form.php
- Windows: localhost/phpclass/form-validate-simple/form.php
Try out the form again, then check your email. Savor the incredible rush of a job well done.
Close any open files. We’re done for now.