Connect with us


Kind Validation with PHP – SitePoint

On this article, we’ll construct and validate a small internet kind utilizing HTML and PHP. The shape is created utilizing HTML, and validation and processing of the shape’s contents is completed with PHP. The purpose of this text is to show you some primary HTML kind components and the way their knowledge is accessible to you in your PHP scripts.

The shape we’ll create incorporates plenty of inputs: textual content fields, a radio button, a multiple-option choose listing, a checkbox, and a submit button. These inputs will probably be validated to make sure that the consumer has equipped a worth for every one.

If a number of fields are empty, the shape will probably be displayed once more. This time, nevertheless, the empty fields will probably be have the error string “Lacking” subsequent to them. If not one of the fields are empty, the equipped values will probably be displayed, in a simplistic vogue.

Yow will discover the code for this text on GitHub.

The HTML Kind

Let’s create the HTML kind. The aim of the shape is for the fictional firm “The World of Fruit” to conduct a fruit survey of their clients. The shape captures three issues:

  • The consumer’s particulars (title, deal with, and e-mail deal with)
  • The consumer’s fruit consumption preferences (quantity of fruit they eat per day, and their favourite fruit)
  • If the consumer would love a free brochure

Textual content Fields

The title, deal with, and e-mail fields will probably be coded with label and enter components like this:

<label for="title">Title</label>
    <enter sort="textual content" title="title" id="title" worth="">

<label for="deal with">Handle</label>
    <enter sort="textual content" title="deal with" id="deal with" worth="">

<label for="e-mail">E mail</label>
    <enter sort="textual content" title="e-mail" id="e-mail" worth="">

HTML enter components have a number of attributes. Setting sort to textual content defines them as single-line enter fields that settle for textual content. The title attribute is used to specify the sector’s title, and is used to entry the aspect throughout PHP processing. The ID attribute associates the enter with its related label (by way of the label’s for attribute), which makes the shape extra accessible.

Radio Buttons

The radio button shops how a lot fruit the consumer eats per day.

  <enter sort="radio" title="howMany" worth="zero"> 0
  <enter sort="radio" title="howMany" worth="one"> 1
  <enter sort="radio" title="howMany" worth="two"> 2
  <enter sort="radio" title="howMany" worth="twoplus"> Greater than 2

Setting sort to radio renders the enter as a radio button. Discover how every button is assigned the identical title. This treats the radio buttons as a gaggle, permitting the consumer to pick 0, 1, or 2. The worth attribute differs for every button to supply the completely different values that the consumer can select from. As a result of the inputs are wrapped inside the labels right here, the for and id attributes aren’t wanted.

Choose Record

The choose aspect shops the consumer’s selection of favourite fruit:

<label for="favoriteFruit">My favourite fruit</label>
  <choose title="favoriteFruit[]" id="favoriteFruit" dimension="4" a number of="">
    <choice worth="apple">Apple</choice>
    <choice worth="banana">Banana</choice>
    <choice worth="plum">Plum</choice>
    <choice worth="pomegranate">Pomegranate</choice>
    <choice worth="strawberry">Strawberry</choice>
    <choice worth="watermelon">Watermelon</choice>

The title attribute is an array (outlined by the sq. brackets after the title) as a result of a number of decisions are allowed (as a result of presence of the a number of attribute). With out the a number of attribute, just one choice can be selectable.

The worth attribute for every choice aspect is the worth that will probably be submitted to the server, and the textual content between the opening and shutting choice tag is the worth the consumer will see within the choose menu. Every choice aspect will need to have a definite worth.


<label for="brochure">Would you want a brochure?</label>
  <enter sort="checkbox" title="brochure" id="brochure" worth="Sure">

A checkbox aspect is used to let the consumer select if they need a brochure or not. Its worth will probably be set to “Sure” if the field is checked. In any other case, it would successfully be set to “No”.

Submit Button

  <enter sort="submit" title="submit" worth="Submit">

Final however not least is the Submit button. The worth of its worth aspect is displayed because the button’s textual content. Clicking on it submits the shape.

The Kind Factor

<kind methodology="POST" 
  motion="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Subsequent comes the kind aspect. Whereas HTML kinds help plenty of attributes, solely two attributes have to be set: motion and methodology. methodology determines how the shape’s content material is submitted. motion defines the place the shape contents are despatched when the shape is submitted.

Setting motion to POST signifies that the shape’s content material is distributed as a part of the HTTP request’s physique. The values are retrievable in PHP by way of the $_POST superglobal. The choice to POST is GET, which passes the shape’s values as a part of the URL. Values despatched utilizing GET are retrievable in PHP by way of the $_GET superglobal.

The primary distinction between the strategies POST and GET is visibility. There are quite a few articles on the Net about selecting between them, however my recommendation is to stay to POST when utilizing kinds, until you’ve a very good motive to move consumer knowledge in a viewable URL.

Within the instance above, motion is ready to the results of passing the worth of $_SERVER["PHP_SELF"], which is the title of the present script being executed, to PHP’s htmlspecialchars() methodology. This methodology is used to transform particular HTML characters to their HTML entity names. for instance, > will probably be transformed to &gt;.

This does two issues:

  1. It prevents the shape from breaking, if the consumer submits HTML markup.
  2. It’s a technique of defending in opposition to XSS (Cross-Web site Scripting) assaults, which attackers will use to attempt to exploit vulnerabilities in internet functions. To search out out about different frequent vulnerabilities, take a look at the OWASP High 10.

Notice: in an actual software, you’d possible use greater than htmlspecialchars to sanitize kind enter, reminiscent of a third-party library like laminas-filter.

Utilizing $_SERVER["PHP_SELF"] is preferable to easily hard-coding a location if you would like your kind to publish again to the identical script that generated it, because you received’t should replace the code for those who change the script’s title.

Simply earlier than we end up discussing kinds, listed below are three issues to recollect when working with HTML kinds:

  • All the shape controls should be enclosed inside the kind tags.
  • The alignment of textual content and kind controls will be achieved in some ways. CSS is the popular choice for this, particularly with all the brand new format instruments obtainable as of late, together with Flexbox and Grid. (Please don’t use tables for format, as kind components usually are not tabular knowledge!)
  • For further accessibility, it’s price trying into the fieldset aspect for grouping kind components.

Kind Processing

Now that you simply’ve outlined the shape in HTML, let’s work via the code that processes the shape. Earlier than we try this, remember that the shape will be in one in every of two states:

  1. A clean kind is loaded when the web page is first loaded.
  2. The shape is loaded if the shape failed validation. On this state, the fields that the consumer crammed out will comprise the worth equipped. The opposite fields will probably be empty with an error message subsequent to them.

Validating the Kind Contents

When the shape is submitted, the next entries will probably be saved within the $_POST array (or $_GET array relying on the shape’s methodology attribute). The values within the left-hand column are taken from the management’s title attribute, and I’ve additionally marked whether or not the sector is a required subject for validation functions.

Area Kind Obligatory or Non-obligatory
title single-value variable necessary
deal with single-value variable necessary
e-mail single-value variable necessary
howMany single-value variable necessary – should choose one
favoriteFruit array necessary – should choose one
brochure single-value variable optionally available

If the consumer doesn’t adjust to these guidelines, an error message will probably be displayed. Any fields already accomplished will probably be left unchanged, permitting the consumer to easily alter their enter and re-submit the shape, with out having to re-enter knowledge.

Earlier than we proceed, the validation that we’re performing within the code on this article is extraordinarily simplistic. Usually, you’d carry out far more subtle validation, reminiscent of:

  • whether or not sure fields usually are not longer than a sure size
  • Whether or not an e-mail deal with meets the e-mail deal with specification
  • if a begin date was of the right format and earlier than or after a sure date

To do this, you’d possible use a third-party library, reminiscent of laminas-validator or the Symfony validation element
Nonetheless, that’s exterior the scope of this text.

Let’s take a look at the PHP required for validating the shape, which is positioned on the prime of the web page, earlier than the HTML for the shape:

$errors = [];
$fields = ['name', 'address', 'email', 'howMany', 'favoriteFruit', 'brochure'];
$optionalFields = ['brochure'];
$values = [];
    foreach ($fields as $subject) {
        if (empty($_POST[$field]) && !in_array($subject, $optionalFields)) {
            $errors[] = $subject;
        } else {
            $values[$field] = $_POST[$field];

The code initializes three arrays:

  • $errors: initially empty, this shops the shape fields that failed validation
  • $fields: this shops all the sector names to be processed
  • $optionalFields: this shops the sector names which can be optionally available
  • $values: initially empty, that is an associative array that can comprise the equipped fields and their values

After that, it checks if the tactic used to submit the shape was set to POST. In that case, it iterates over the values within the array and checks if the $_POST superglobal incorporates the related subject title. In that case, and the sector has a worth, the sector and its worth is saved within the $values array. Nonetheless, if the sector is empty, and it’s not within the $optionalFields array, it’s added to the $errors array.

Within the instance right here, we’re checking the $_POST array as a result of the shape’s methodology is ready to POST. If methodology was set to GET, the code can be up to date to verify the $_GET superglobal as a substitute.

After checking the submission for errors, in a somewhat rudimentary means, the code prints out the values that the consumer submitted, if no errors have been recorded:

    if (empty($errors)) {
        foreach ($fields as $subject) {
            if ($subject === "favoriteFruit") {
                printf("%s: %s<br />", $subject, var_export($_POST[$field], TRUE));
            } else {
                printf("%s: %s<br />", $subject, $_POST[$field]);

After working this code, the HTML for the web page is rendered. Provided that we’re going to render the shape once more with the values the consumer equipped, we have to replace the shape somewhat. Particularly, some PHP code must be integrated into the HTML for every aspect.

For the enter fields, we’ll replace them to set their values as within the following instance, which populates the worth of the title subject:

<enter sort="textual content" 
       worth="<?php echo htmlspecialchars($values['name']);?>">

htmlspecialchars() is used right here for a similar motive it was used earlier with PHP_SELF – to guard in opposition to XSS assaults. Then the next HTML will probably be added after the enter subject to show an error message if a worth wasn’t equipped:

<?php if (in_array('title', $errors)): ?>
  <span class="error">Lacking</span>
<?php endif; ?>

Form submitted but with errors

The usage of the category error offers a hook for styling the error message utilizing CSS:

.error {
  shade: #FF0000;

Extending the Kind’s Usability

With somewhat extra effort, you can even keep in mind the alternatives the consumer produced from the radio buttons and choose:

<enter sort="radio" title="howMany"
 <?php if (isset($howMany) && $howMany == "zero") echo "checked"; ?>
 worth="zero"> 0
<enter sort="radio" title="howMany"
 <?php if (isset($howMany) && $howMany == "one") echo "checked"; ?>
 worth="one"> 1
<enter sort="radio" title="howMany"
 <?php if (isset($howMany) && $howMany == "two") echo "checked"; ?>
 worth="two"> 2
<enter sort="radio" title="howMany"
 <?php if (isset($howMany) && $howMany == "twoplus") echo "checked"; ?>
 worth="twoplus"> Greater than 2

Code has been added to verify whether or not the variable related to the radio button has been outlined inside the validation part. In that case, checked is outputted as a part of the aspect’s HTML.

Now to handle the choose menu. It’s truly a greater concept to restructure the code as a loop than to blindly add code to verify every choice manually. The loop can generate the HTML for the choices on the fly, and the verify for whether or not the choice has been chosen or not will be integrated into it:

<choose title="favoriteFruit[]" dimension="4" a number of="">
$choices = ["apple", "banana", "plum", "pomegranate", "strawberry", "watermelon"];
foreach ($choices as $choice) {
        '<choice worth="%s" %s>%s</choice>',
        (in_array($choice, $values['favoriteFruit'])) ? "chosen" : '', ucfirst($choice)

If you happen to’re not but accustomed to PHP loops, chances are you’ll need to learn the “Studying Loops” article.

Notice that the distinction right here is the usage of the attribute chosen: radio buttons use checked, whereas choose choices use chosen. It’s simply a kind of minor inconsistencies we now have to reside with.

One subject that I haven’t addressed and is exterior the scope of this text is what you’d do with the info after validation is profitable. There are a selection of prospects, together with saving it in a database or emailing the info to your self. Whichever you select, it’s essential make certain that:

  • the shape has been submitted by the consumer
  • the info entered by the consumer is error-free


Validation is crucial, significantly for those who’re going to save lots of the submitted knowledge in a database, or another type of persistent storage. When validating, it pays to recollect the outdated saying GIGO (Rubbish In, Rubbish Out), and also you received’t go far incorrect.

On this article, you’ve discovered 4 issues:

  • find out how to create a primary HTML kind
  • find out how to validate the shape with PHP
  • find out how to re-display consumer enter
  • find out how to show error messages

For additional data on $_SERVER, $_POST, and $_GET, learn the article “Introducing Superglobals” and, after all, the PHP documentation.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *