HTML5

Process HTML Forms With PHP

Working with Forms when building websites seems so easy. There are in fact many details to be aware of. We’ll take a...

Written by Luci · 8 min read >

Working with Forms when building websites seems so easy. There are in fact many details to be aware of. We’ll take a look at the POST super global, and how it ties in to processing forms in PHP. Let’s jump right in!

3 Ways To Get User Data

  • Links and URLs By making use of a query string, key / value pairs of data can be passed via the GET super global
  • Forms With HTML Forms, POST is the usual method of data transfer and does not require encoding / decoding the way Links and URLs do
  • Cookies By setting cookie values via PHP, you can then read and write data to an associative array as needed

In this adventure we’ll be specifically targeting the 2nd approach with POST requests and HTML Forms in PHP. It is by the $_POST super global variable that we can access data submitted by the form. The various fields in the HTML Form will have a name attribute which will then become the key of the associative array in $_POST. You can make use of form processing via a 2 page process, or a single page form process. There are pros and cons to each, and for now we’ll take a look at the 2 page approach. What this means is that your first page will contain the HTML markup for the form. That form will have an action attribute, and the value of that attribute is the second PHP page that will process the data. The easiest way to see how this works is to create it in code.

<html>
  <head>
    <meta charset="utf-8">
    <title>HTML Form Built With Love</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>

  <body>
    <form action="process_form.php" method="post">
       Website: <input type="text" name="website" value="" /><br>
       Category: <input type="text" name="category" value="" /><br><br>

       <input type="submit" name="submit" value="Submit Website" />
    </form>
  </body>
</html>
<?php
print_r($_POST);
?>

So there we have our two page setup for form processing at its most very basic. If we load up form.php in our browser, we can enter some information into the form. In the first field we will enter https://learnjs.co and in the second we’ll enter Development. Then we’ll hit the Submit Button and see what happens.

Array
(
[website] => https://learnjs.co
[category] => Development
[submit] => Submit Website
)

Very Cool! You can see how the name attribute became the key in our array, and the data we typed became the value of that particular key. This data was passed from page one to page to via the POST method. Let’s look at grabbing the data out of that array and actually using it. In your actual programs, the sky is the limit in terms of how you can process this information. Let’s just grab the two values, put them in variables, then use them on the page somehow. We’ll update the process_form.php file like so and see what we can do.

<html>
  <head>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>

  <body>

    <?php
      $website = $_POST['website'];
      $category = $_POST['category'];

      echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
    ?>

  </body>
</html>

Hi bud, thanks for submitting https://learnjs.co to the Development category.

Now that we have an understanding of how to create a basic HTML form on one page, and a PHP processing script on another, let’s now look at how to detect if there was a form submission. This is a common and necessary step with processing forms in PHP. There are many reasons for this, but one of the main ones is if a user tries to load the form processing page directly, as this will cause errors in your application. So what’s the best way to do this? Let’s have a look.

Detecting Form Submission

Set Default Values

One thing we can do is set up some logic to assign default values if needed. This way if the user submits the actual form processing page instead of the HTML form itself, we can set values to something sensible as needed. Using the ternary operator is an easy way to do this.

<html>
  <head>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>

  <body>

    <?php
      $website = isset($_POST['website']) ? ($_POST['website']) : 'http://learnjs.co' ;
      $category = isset($_POST['category']) ? ($_POST['category']) : 'Development' ;

      echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
   ?>

  </body>
</html>

Loading the this page directly will provide “Hi bud, thanks for submitting http://learnjs.co to the Development category.”, however loading if you submit a blank form from form.php, the processing page will still run but it will have empty values.

A Better Form Detection Method

The prior example is a start, but there is an easier and better way. Let’s revise the form processing script to have the following format.

<html>
  <head>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>

  <body>

    <?php

      if(isset($_POST['submit'])) {
	      echo 'Nice Form Submission!<br>';
      } else {
	      echo 'Stop trying to hack the form fool!';
	      exit;
      }

      $website = isset($_POST['website']) ? ($_POST['website']) : 'http://learnjs.co' ;
      $category = isset($_POST['category']) ? ($_POST['category']) : 'Development' ;

      echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
?>

</body>
</html>

This is great and now provides something more along the lines of what you’d be looking for. If a user submits valid data to the form, and then hits the submit button, it may look like this.

Nice Form Submission!
Hi bud, thanks for submitting learnjs.co to the Development category.

If the user tries to load process_form.php directly however, they are provided this message.

Stop trying to hack the form fool!

What we are doing is checking for the presence of the submit key in the $_POST array. The only time that key is present is if a user actually clicked on the submit button in the form, so this is the way to most easily detect form submission.

Single Page Form Submission

Another way to approach dealing with forms and form submission in PHP is to simply complete the form processing on the same page as the HTML form. Let’s see how to do this.

<?php

if(isset($_POST['submit']) and strlen($_POST['website']) > 0) {
	$website = htmlspecialchars($_POST['website']);
	$category = htmlspecialchars($_POST['category']);
	echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
} else {
	echo 'Enter a Website and Category';
}

?>
<html>
  <head>
    <meta charset="utf-8">
    <title>HTML Form Built With Love</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>

  <body>

    <form action="form.php" method="post">
       Website: <input type="text" name="website" value="" /><br>
       Category: <input type="text" name="category" value="" /><br><br>

       <input type="submit" name="submit" value="Submit Website" />
    </form>

  </body>
</html>

Now when this page is loaded initially, or if a blank form is submitted, the user gets the message, Enter a Website and Category . If the user provides something like http://learnjs.co and Development then clicks submit, they will get a message like Hi bud, thanks for submitting http://learnjs.co to the Development category. 

Basic Form Validation

In this day and age, using a PHP framework like Laravel, Symfony, Zend, Codeigniter, Yii, or any of the many other fantastic solutions is the way to go with doing things like Form Validation. It is still important to know the underpinnings of how these frameworks do their magic, and in order to have that we need to understand PHP itself at the most basic levels. So what are some of the things one would typically validate for? Let’s examine.

Validation Characteristics

  • Presence Did the user actually enter anything into a given field?
  • String Length Is the string provided long enough to warrant a valid value?
  • Type Check Checking the type of data is quite common.
  • Inclusion If there is a drop down list of 10 values, is the value provided one of those 10 possible values?
  • Uniqueness Is the data a user is submitting 100% unique? This is common on email address submissions.
  • Format Does the website address contain http:// or does an email contain an @ symbol, etc..

This is the proverbial tip of the iceberg here, as data validation can have hundreds of characteristics, but remember young Jedi, we’re talking about the basics in this episode. So let’s see what these types of validation rules might look like in basic PHP.

<?php

// presence
$value = '';

if(!isset($value) or empty($value)) {
    echo 'fail';	
}

// string length
$value = '';
$min = 2;
$max = 25;

if(strlen($value) < $min) {
	echo 'fail - too small';
}

if(strlen($value) > $max) {
	echo 'fail - too big';
}

// type
$value = '';
if(!is_string($value)) {
	echo 'fail - not a string';
}

// set inclusion
$value = '7';
$set = array('1', '2', '3', '4', '5', '6', '7', '8');
if(!in_array($value, $set)) {
	echo 'fail - not in the set';
}

// format
$value = 'tom@jones.com';
if(!preg_match('/@/', $value)) {
    echo 'not a valid email';
}

?>

Validation Functions

When not using a full blown framework, the next best thing is to put your validation logic into reusable functions. Here are some examples we can use to test out on our single page form validation example.

<?php

function has_presence($value) {
	return isset($value) and $value !== '';
}

function max_length($value, $max) {
	return strlen($value) <= $max;
}

function min_length($value, $min) {
	return strlen($value) >= $min;
}

function has_inclusion($value, $set) {
	return in_array($value, $set);
}
 
function form_errors($errors = array()) {
	$output = '';
	if(!empty($errors)){
		$output .= '<div class="alert alert-danger">';
		$output .= 'You might need to fix a few things!<br>';
		$output .= '<ul>';
		foreach($errors as $key => $error) {
			$output .= '<li>'. $error .'</li>';
		}
		$output .= '</ul>';
		$output .= '</div>';
	}
	return $output;
} 

?>

Now we can include this file right into our form page just like this.

<?php
include('validation_functions.php');
$errors = array();
 
// was the form submitted?
if(isset($_POST['submit'])) {
    $website = htmlspecialchars($_POST['website']);
    $category = htmlspecialchars($_POST['category']);
	
	// is the website field present?
	if(!has_presence($website)) {
		$errors['website'] = 'You need to enter a website!';
	}
	
	// is the website address at least 4 characters or more?
	if(!min_length($website, 4)) {
		$errors['minlength'] = 'The website must be 4 characters or more!';
	}
	
	// is the category field present?
	if(!has_presence($category)) {
		$errors['category'] = 'You need to provide a category!';
	}
	
    if(empty($errors)) {
		    echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
	}

} else {
    echo 'Enter a Website and Category';
}

?>
<html>
  <head>
    <meta charset="utf-8">
    <title>HTML Form Built With Love</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/respond.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </head>
 
  <body>
 
    <form action="form.php" method="post">
       Website: <input type="text" name="website" value="" /><br>
       Category: <input type="text" name="category" value="" /><br><br>
 
       <input type="submit" name="submit" value="Submit Website" />
    </form>

   <?php echo form_errors($errors); ?>

  </body>
</html>

Fantastic! We now have a fully functioning HTML form which is processed via PHP on the same page, uses validation functions to handle validation, and outputs any errors in a nice list format if something goes wrong.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile

7 Alternatives to the div Tag in HTML

Luci in HTML5
  ·   6 min read
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x