PHP Solution 5-1: Making Sure Required Fields Aren't Blank
PHP Solution 5-1: Making Sure Required Fields Aren't Blank
When required fields are left blank, you dont get the information you need and the user may never get
a reply,
particularly if contact details have been omitted.
Continue using the file from the previous exercise. Alternatively, use contact_02.php from the ch05
folder and
remove _02 from the filename.
1. The processing script uses two arrays called $errors and $missing to store details of
errors and required fields that havent been filled in. These arrays will be used to control
the display of error messages alongside the form labels. There wont be any errors when
the page first loads, so initialize $errors and $missing as empty arrays in the PHP code
block at the top of contact.php, like this:
<?php
include './includes/title.php';
$errors = [];
$missing = [];
?>
2. The email-processing script should run only if the form has been submitted. As Figure 5-2
shows, the $_POST array contains a name/value pair for the Submit button, which is called
send in contact.php. The value of $_POST['send'] will be defined (set) only if the form
has been submitted. So you can use a conditional statement and the isset() function to
control whether to run the processing script. Add the code highlighted in bold to the PHP
block at the top of the page.
<?php
include './includes/title.php';
$errors = [];
$missing = [];
// check if the form has been submitted
if (isset($_POST['send'])) {
// email processing script
}
?>
Note T he name attribute of the Submit button in this form is send. If you give your Submit
3. Although you wont be sending the email just yet, define two variables to store the
destination address and subject line of the email. The following code goes inside the
conditional statement that you created in the previous step:
if (isset($_POST['send'])) {
// email processing script
$to = '[email protected]'; // use your own emai