PHP Forms

Forms are an important part of most PHP web applications as PHP is well-suited for handling the data received from a form. Of course, before data can be received, there has to be a form for the user to submit.

HTML Forms

HTML forms are used for many purposes, from search boxes to shopping carts. But ultimately, they are used to collect data from the user. Take the following example below. This form is requesting a user's name.

<form>
  <label>Name:</label><input type="text" name="name">

  <button type="submit">Submit</button>
</form>

But want happens after the submit button has clicked. By default, a form will cause data to be submitted to the page the form resides using the HTTP GET method. This means the values the user enters will be sent through the URL. Except for a search box, this is typically not the behaviour we want.

To override how the form sends the data, we can add a method attribute and set its value to POST.

<form method="POST">
  <label>Name:</label><input type="text" name="name">

  <button type="submit">Submit</button>
</form>

Now the data will be submitted using the HTTP POST method, which is more secure and not limited by the size of the data sent. Most HTML forms for web applications will use the POST method.

In addition to the method, we can also alter the page to which the form submits using the action attribute. This can be beneficial if the PHP code handles the form data on a different page from the form.

<form method="POST" action="submit.php">
  <label>Name:</label><input type="text" name="name">

  <button type="submit">Submit</button>
</form>

In the example above, the form will submit the form data to the submit.php file. Next, let's look at how we can retrieve data being sent using the HTTP POST method.

$_POST

This YouTube video was created by Steve Griffith.

The $_POST variable is an associative array of variables that passed the current script via the HTTP POST method when receiving data from a form.

For example, let's say we have the following HTML form.

<form method="POST" action="submit.php">
  <label>Name:</label><input type="text" name="name" value="World">

  <button type="submit">Submit</button>
</form>

If submitted, the form will submit to the submit.php file using the HTTP POST method. Therefore, the submit.php script will retrieve the data using the $_POST variable.

// submit.php
<?php 
  echo "Hello, {$_POST['name']}"; 
?>

The above example will output something similar to:

Hello, World

Now that we know how to retrieve the data from a form, we will next examine how we can validate the data to ensure that the data we are using is complete and safe.

Validating a Form Input

It is important to validate any data received from users. Even users without malicious intent can make mistakes when provided data. In this section, we will cover the basic validation of data.

Before we can being validating data, we will make sure that there is data to be validated. This can be done using $_SERVER['REQUEST_METHOD'] property, which tells which request method was used to access the page.

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // form has submitted using HTTP POST method 
}

In the above example, we are only testing to see if the page is being viewed using the POST method. We can take this a step further and test to see if the $_POST array contains the data. We can use the isset function to do this.

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // form has submitted using HTTP POST method 
  if (isset($_POST['name'])) {
    // name input is in the $_POST array
  }
}

Next, we will the trim and empty functions to test if a value has been submitted with the form input. The trim function will strip whitespace from the beginning and the end of a string. The empty function will determine if a variable or array key has a value that is not an empty string, 0, or NULL.

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // form has submitted using HTTP POST method 
  if (isset($_POST['name'])) {
    // name input is in the $_POST array

    // trim white space from name input 
    $data = trim($_POST['name']);

    if (empty($data)) {
      // no value for name input 
    } else {
      // name input has a value
    }
  }
}

After we have determined that there is data, we need to sanitize the data. We use the stripslashes, and htmlspecialchars functions to do this. The stripslashes function will remove all escape characters (\) from a string. The htmlspecialchars function converts special characters to HTML entities. This step is important to help make any malicious code ineffective.

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // form has submitted using HTTP POST method 
  if (isset($_POST['name'])) {
    // name input is in the $_POST array

    // trim white space from name input 
    $data = trim($_POST['name']);

    if (empty($data)) {
      // no value for name input 
    } else {
      // name input has a value

      // sanitize name input value
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
    }
  }
}

Form Validation

Now that we see the basics of form validation let's create a validation system for the entire form. We start by creating arrays for all fields, optional fields, any errors we might encounter, and the final values that will be stored. We will walk through each expected field, ensuring that required fields have values, then each input is sanitized.

If any validation error is found, the form will display a message next to the input.

NOTE

In this example, we are only checking that required inputs are not empty. But in a real project, we will want to make sure that they are properly formatted.

<?php
$inputs = ['first_name', 'last_name', 'email', 'phone'];
$optional = ['phone'];
$errors = [];
$values = [];

function sanitize ($data) {
  return htmlspecialchars(stripslashes($data));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  foreach ($inputs as $input) {
    if (isset($_POST[$input])) {
      $data = trim($_POST[$input]);

      if (empty($data) && !in_array($input, $optional)) {
        array_push($errors, $input);
      } else {
        $values[$input] = sanitize($data);
      }     
    }
  }  
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Validation</title>
</head>
<body>
  <form method="post">
    <div>
      <input type="text" name="first_name" placeholder="First Name" value="<?php echo isset($values['first_name']) ? $values['first_name'] : ""; ?>">
      <?php if (in_array('first_name', $errors)) : ?>
      <span>This input is required</span>
      <?php endif; ?>
    </div>
    <div>
      <input type="text" name="last_name" placeholder="Last Name" value="<?php echo isset($values['last_name']) ? $values['last_name'] : ""; ?>">
      <?php if (in_array('last_name', $errors)) : ?>
      <span>This input is required</span>
      <?php endif; ?>
    </div>
    <div>
      <input type="text" name="email" placeholder="Email" value="<?php echo isset($values['email']) ? $values['email'] : ""; ?>">
      <?php if (in_array('email', $errors)) : ?>
      <span>This input is required</span>
      <?php endif; ?>
    </div>
    <div>
      <input type="text" name="phone" placeholder="Phone" value="<?php echo isset($values['phone']) ? $values['phone'] : ""; ?>">
    </div>
    <button type="submit">Submit</button>
  </form>
</body>
</html>