From validation with PHP

In this article, we’ll build and validate a small web form using HTML and PHP. The form is created using HTML, and validation and processing of the form’s contents is done with PHP. The goal of this article is to teach you some basic HTML form elements and how their data is accessible to you in your PHP scripts.

The form we’ll create contains a number of inputs: text fields, a radio button, a multiple-option select list, a checkbox, and a submit button. These inputs will be validated to ensure that the user has supplied a value for each one.

If one or more fields are empty, the form will be displayed again. This time, however, the empty fields will be have the error string “Missing” next to them. If none of the fields are empty, the supplied values will be displayed, in a simplistic fashion.

You can find the code for this article on GitHub.

The HTML Form

The initially loaded form

Let’s create the HTML form. The purpose of the form is for the fictitious company “The World of Fruit” to conduct a fruit survey of their customers. The form captures three things:

  • The user’s details (name, address, and email address)
  • The user’s fruit consumption preferences (amount of fruit they eat per day, and their favorite fruit)
  • If the user would like a free brochure

Text Fields

The name, address, and email fields are text input elements and can be coded like this:

Name <input type="text" name="name" value=""> Address <input type="text" name="address" value=""> Email <input type="text" name="email" value=""> 

HTML input elements can have several attributes, the most important of which are the type and name.
Setting type to text defines them as single-line input fields that accept text. The name attribute is used to specify the field’s name, and is used to access the element during process in PHP code.

Radio Buttons

The radio button stores how much fruit the user eats per day.

<input type="radio" name="howMany" value="zero"> 0 <input type="radio" name="howMany" value="one"> 1 <input type="radio" name="howMany" value="two"> 2 <input type="radio" name="howMany" value="twoplus"> More than 2 

Setting type to radio renders the input as a radio button. Notice how each button is assigned the same name. This treats the radio buttons as a group, allowing the user to select 0, 1, or 2. The value attribute differs for each button to provide the different values that the user can choose from.

Select List

The select element stores the user’s choice of favorite fruit:

<select name="favoriteFruit[]" size="4" multiple> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="plum">Plum</option> <option value="pomegranate">Pomegranate</option> <option value="strawberry">Strawberry</option> <option value="watermelon">Watermelon</option> </select> 

The name attribute is an array (defined by the square brackets after the name) because multiple choices are allowed (because of the presence of the multiple attribute). Without the multiple attribute, only one option would be selectable.

The value attribute for each option element is the value that will be submitted to the server, and the text between the opening and closing option tag is the value the user will see in the select menu. Each option element must have a distinct value.

Checkbox

<input type="checkbox" name="brochure" value="Yes"> 

A checkbox element is used to let the user choose if they want a brochure or not. Its value will be set to “Yes” if the box is checked. Otherwise, it will effectively be set to “No”.

Submit Button

<input type="submit" name="submit" value="Submit"> 

Last but not least is the submit button. The value of its value element is displayed as the button’s text. Clicking on it submits the form.

The Form Element

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 

Next comes the form element. While HTML forms support a number of attributes, only two attributes need to be set: action and method. method determines how the form’s content is submitted. action defines where the form contents are sent when the form is submitted.

Setting action to POST means that the form’s content is sent as part of the HTTP request’s body. The values are retrievable in PHP via the $_POST superglobal. The alternative to POST is GET, which passes the form’s values as part of the URL. Values sent using GET are retrievable in PHP via the $_GET superglobal.

The main difference between the methods POST and GET is visibility. There are numerous articles on the Web about choosing between them, but my advice is to stick to POST when using forms, unless you have a good reason to pass user data in a viewable URL.

In the example above, action is set to the result of passing the value of $_SERVER["PHP_SELF"], which is the name of the current script being executed, to PHP’s htmlspecialchars() method. This method is used to convert specific HTML characters to their HTML entity names. for example, > will be converted to &gt;.

This does two things:

  1. It prevents the form from breaking, if the user submits HTML markup
  2. It is a means of protecting against XSS (Cross-Site Scripting) attacks, which attackers will use to try to exploit vulnerabilities in web applications. To find out about other common vulnerabilities, check out the OWASP Top 10.

Note: in a real application, you’d likely use more than htmlspecialchars to sanitize form input, such as a third-party library like laminas-filter.

Using $_SERVER["PHP_SELF"] is preferable to simply hard-coding a location if you want your form to post back to the same script that generated it, since you won’t have to update the code if you change the script’s name.

Just before we finish up discussing forms, here are three things to remember when working with HTML forms:

  • All the form controls must be enclosed within the form tags.
  • The alignment of text and form controls can be achieved in many ways. CSS is the preferred option for many. However, be prepared to see tables used for alignment in older HTML.
  • Not discussed here – but important for accessibility – is the label element.

Form Processing

Now that you’ve defined the form in HTML, let’s work through the code that processes the form. Before we do that, be aware that the form can be in one of two states:

  1. A blank form is loaded when the page is first loaded.
  2. The form is loaded if the form failed validation. In this state, the fields that the user filled out will contain the value supplied. The other fields will be empty with an error message next to them.

Continue reading Form Validation with PHP on SitePoint.

Similar Posts