Freeola Internet Get Dotted Domains Blog Guides Chat

Viewing Thread:
'Basic validation of your HTML web form, server-side, using PHP'

Sun 11/02/07 at 23:41:
cjh
Regular
"It goes so quickly"
Posts: 4,104
Basic validation of your HTML web form, server-side, using PHP

As mentioned in a previous article, Client-side validation using JavaScript can be a quick and easy way to validate a web form, because it is done by the users web browser. An alert box can be used to tell the user that a particular form field isn’t filled in as expected, and the web form can be prevented from submitting until the field is filled in as required.

The main downfall of current client-side scripting is that JavaScript may not be supported in older web browsers, or browsers that are used via a screen reader, or a mobile phone browser. Current web browsers also allow the user to turn of JavaScript completely, meaning any client-side validation is just ignored.

Server-side validation ensures that no matter what, user inputted data can be reviewed before being accepted. The user can’t turn it off, and a screen reader or mobile phone doesn’t need any additional software to use it. Your web server will take care of everything.

PHP is a server-side scripting language that Freeola allow it’s customers to make use of, free of charge, as part of their web hosting package, which makes it the perfect choice for a small server side validation script. This little article will show you how, but rather than explain the whole PHP process, will just dive right in and show you how it’s done. Learning PHP in itself is a topic on it’s own (that will no doubt appear at some point).

This guide will assume you’ve already created your HTML web form, and at least read over the Client-side validation using JavaScript thread. This guide isn’t aimed at teaching you PHP as a whole, just how to make use of it for basic form validation.

The good news is that PHP code will look similar to JavaScript, so it won’t be as overbearing as you may think.

So lets get straight in to it ...

With PHP, you can combine the HTML web form and server-side validation in to a single file. Doing this can be a little trickier to achieve, but will make filling in the form easier for the user, the biggest advantage being that you can keep the valid data already filled in, without the web browser deleting it.

The Form to Mail script that Freeola offer directs the user to a new web page before the validation is done, and requires the user to click back if a problem is found. Some web browsers unfortunately do not remember what the user has typed in, presenting them with a blank form, even though they have filled it in.

To start off, you’ll need to rename your web form file from being a .htm or .html file to being a .php file, for example, myform.htm will need to become myform.php. This is so the Freeola web servers know that the file contains PHP code that needs to be “parsed”.

Because the entire form validation will be done via a single file, you’ll need to alter parts of your HTML code to fit the PHP code within it. For example:





You’ll notice that that value within the action attribute is no longer a standard web address, but is a little PHP code that will automatically fill in this bit for you. The value that’ll appear in your HTML will be the address of your current web form.

represents the beginning of the PHP code, while ?> represents the end of the PHP code. Anything between and ?> is looked over by the Freeola web server and run according to the PHP code. In the above example, the code is saying, “place the name and location of this file here”.

Because of this, we’re going to effectively split the page in to two parts, one with the HTML web form, and the other with the validation and thank you for the submission to the user. The thank you segment will be where you can place the required PHP code to use the users data, whether you’re mailing it to yourself, saving to a file or storing it on a database.

Because the code will contain a ‘thank you’, we’ll need to place it within the element, otherwise the user won’t see it. There are other ways to achieve this, but we want to keep it simple for now. The best place to include the PHP code would be just above the HTML form.

We’ll first need to set two PHP variables. Variables in PHP are defined with a dollar sign ($), followed by the name of the desired variable, then an equals sign (=) and the value that you want to assign, usually with quotation marks for standard text.


// Start PHP.
$showform = TRUE;
$error = "";


The variable $showform will be set to TRUE, because we want to see the web form first. The variable $error will be set as being empty, as we will us it to contain our error message if any validation problems occur. With each validation error, this variable will have an error message added to it.

Next up, we will put the validation code. There is no point in running the code if the form hasn’t been submitted, which will only happen when the user first comes to the web page. Naturally, when this is the case, they would not have had the opportunity to fill in the form, so wouldn’t expect any error messages at this stage.

When a web form is submitted, all the form field names and values are automatically stored in a PHP global array, as either $_GET or $_POST, depending on which method you’ve used on your web form. The examples here assume you’ve used action= “post” in your HTML, but if not, replace all references from $_POST to $_GET. For name of each form field is used within this array, so a form field with the name attribute set to firstname would be referenced from the array as $_POST[‘firstname’].

Because of this, we can check for the existence of the submit button, which will only be there if the form was submitted. The code for this (assuming the name value of the submit is submit) is:


if (isset($_POST['submit'])) { // Form has been submitted.
// form validation goes here
}


The form validation code is blocked within the above to ensure none of it is run unless the form has been submitted.

Within this block, we can then create individual variables for each of our form fields. This is done to make typing out each variable a little easier later on. This also gives us a chance to trim any white space from each entry that may appear if the user presses the space bar by mistake.

There is more than one way to do this. All the examples below will result in the same outcome, which is the creation of a variable that either holds the data the user entered for a particular field, or an empty value.

Pick one of the examples below, and copy it for each of your form fields, first name, last name, email, etc.

1:
$firstname = (isset($_POST['firstname'])) ? trim($_POST['firstname']) : "";


2:

if (isset($_POST['firstname'])) {
$firstname = trim($_POST['firstname']);
} else {
$firstname = “”; // Create empty value.
}


3:

$firstname = “”; // Set variable first, as empty.

if (isset($_POST['firstname'])) {
$firstname = trim($_POST['firstname']);
}


We’ve now got our variables created and holding any data the user may have submitted. Because we no longer need the $_POST global variable, we can use the unset function to delete it. Doing this allows the Freeola web servers to free up the memory that it takes up.


// Clear global variable.
unset($_POST);


Now it’s time to check it all. Before that though ...

That was valid, where has it gone?

During the validation, the user may enter some data that validates, and some that does not. We want to automatically place the valid information back in to the form fields for the user, so that they don’t loose it every time and become annoyed. This can be done simply by printing the value of the assigned variable in the right place using, for example, within the value attribute of the element asking for the users email address.


Email Address:




In PHP echo means ‘to print’, while the @ is used to hide any PHP error message that might appear. These can look quite ugly on a page, so it’s best to hide them from the user, otherwise they may get a bad impression. The function stripslashes is used because quotation marks are automatically escaped on Freeola customer sites. If we don’t use the stripslashes function here, then every time the user uses a quote, the result would be a slash in front of it.

Was that field empty?

Because we’ve used the trim function when defining our variables which contain the form data, we can now use the handy empty function to check for …. you guessed it, empty fields.

We’ll use the same method of code as above to check for an empty first and last name form field, which can be seen below:


$error .= (empty($firstname)) ? "
  • Please include your first name.
  • " : "";
    $error .= (empty($lastname)) ? "
  • Please include your last name.
  • " : "";


    If a first name or last name hasn’t been entered, the empty function will trigger, and the error message variable $error , will have the required text added to it.

    Remember the dot equals .= means that the text is added to the end of the variable, and does not overwrite it. Using this method, we can build our error message as an HTML list.

    As mentioned above, the user may have entered their name as required, so we’ll want to keep it for them, even if other parts of the form fail to validate. This can be done by adding the required code to the respected value attributes, such as:


    " …>
    " …>


    Validate email address format

    If you’ve read the Client-side validation using JavaScript article, the regular expression may look familiar to you; familiar in the sense that it looks like total gibberish of course. It checks the format of the email address to ensure it is correctly set out. It should catch the majority of incorrectly formatted email addresses.

    PHP uses the case-insensitive function eregi to examine content with a regular expression. The code below will check that the email address entered by the user looks like an email address. If the PHP function doesn’t think it does, it’ll add our error message.

    You will need to remove the “(SPACE)” bit, as this was added due to Freeola limitations on the web forum.


    // Check for a valid email address.
    if (!eregi("^[a-z0-9]+([\.-]([a-z0-9]+))* (SPACE) @([a-z0-9]+(\.[a-z0-9]+)* (SPACE) (-([a-z0-9-]+([a-z0-9]+)))*) (SPACE) (\.[a-z]{2,4})$", $email))
    $error .= "
  • Please enter a valid email address.
  • ";


    Matching Passwords

    As explained in the previous article, users are usually asked to confirm their chosen password when signing up to a web site to ensure they’ve typed it in correctly. PHP can easily accommodate this in a similar manor to JavaScript, with a simple “Do this match that” piece of code, such as $password == $pwconfirm. The double equals sign is required to ensure the two values are compared, rather than the first taking the value of the second.

    Because we only want to alert the user if the password don’t match, we used the PHP “not equals” code, which is the same as JavaScript. If the passwords don’t match, the user is told this. However, if they do match, the password is then checked to ensure it is not less than 10 characters, using the strlen function, which counts how many characters there are.

    The code to do this is shown below, which includes the error message:


    if ($password != $pwconfirm)
    $error .= "
  • Your passwords do not match.
  • ";
    else
    $error .= (strlen($password) < 10) ? "
  • Please enter a desired password, containing 10 or more characters, and then confirm it.
  • " : "";


    There is little point in checking the length of the confirmed password, as it would have already been caught if it weren’t the same as the original password entry.

    For security reasons, it is recommended that you don’t include the users entered password within the HTML when other errors are found.

    Lickity-tick; are you firing blanks?

    Checking to see if the checkbox has been ticked and a selection has been made from the bullet point (or radio) selection list is relatively simple in PHP. Because selecting an option or ticking the box sends the value of the form control when the page is submitted, we can just check for that value, in the same way we would for a text entry form control. The full piece of code for each, including the error message, is shown below:

    Radio selection list:

    // Check the gender selection - one must be selected.
    $error .= (empty($gender)) ? "
  • Please select your gender.
  • " : "";


    Checkbox:

    // Check terms and conditions acceptance - this must be selected.
    $error .= (empty($tandc)) ? "
  • Please confirm that you agree to the terms and conditions.
  • " : "";


    The difference here is ensuing that the selections are kept if the validate, but other aspects of the form don’t. It isn’t a case of filling in the value attribute for a radio selection list or checkbox, but including the attribute checked="checked" within the correct element. This is the attribute that pre-selected a form control.

    To do this, we’ll still include some PHP within the element, but rather than just using the print value code, we’ll use similar code to the above, checking for a specific value that matches that of the form control, and printing out the checked="checked" where it is required.

    Using the checkbox as an example, the code to achieve this would be:


    … which can be read as “If the variable $tandc hold the value accepted, then the user ticked it, so include the HTML code checked="checked", so it is pre-ticked for them.”.

    The code to achieve this needs to be placed within the element, so that if the attribute is printed, it appears in the correct place.


    >


    Be sure to include a space, so that it and the previous attribute don’t sit right next to each other, so the resulting HTML is value="accepted" checked="checked" (space between attributes) and not value="accepted"checked="checked" (no space between attributes).

    With the above code, if the user ticked the checkbox, it’ll be ticked for them again if other errors are found.

    To cater to radio selection lists, you’ll need to enter similar code for each radio form control, substituting the value of the element in each case, which when using our gender example, may look like this:


    >Female
    >Male


    Because the same variable $gender is used for each radio option for this particular group of options, only the option selected by the user will be pre-selection again (unless the user didn’t select any to begin with).

    This same method can be applied to and


    In PHP echo means ‘to print’, while the @ is used to hide any PHP error message that might appear. These can look quite ugly on a page, so it’s best to hide them from the user, otherwise they may get a bad impression. The function stripslashes is used because quotation marks are automatically escaped on Freeola customer sites. If we don’t use the stripslashes function here, then every time the user uses a quote, the result would be a slash in front of it.

    Was that field empty?

    Because we’ve used the trim function when defining our variables which contain the form data, we can now use the handy empty function to check for …. you guessed it, empty fields.

    We’ll use the same method of code as above to check for an empty first and last name form field, which can be seen below:


    $error .= (empty($firstname)) ? "
  • Please include your first name.
  • " : "";
    $error .= (empty($lastname)) ? "
  • Please include your last name.
  • " : "";


    If a first name or last name hasn’t been entered, the empty function will trigger, and the error message variable $error , will have the required text added to it.

    Remember the dot equals .= means that the text is added to the end of the variable, and does not overwrite it. Using this method, we can build our error message as an HTML list.

    As mentioned above, the user may have entered their name as required, so we’ll want to keep it for them, even if other parts of the form fail to validate. This can be done by adding the required code to the respected value attributes, such as:


    " …>
    " …>


    Validate email address format

    If you’ve read the Client-side validation using JavaScript article, the regular expression may look familiar to you; familiar in the sense that it looks like total gibberish of course. It checks the format of the email address to ensure it is correctly set out. It should catch the majority of incorrectly formatted email addresses.

    PHP uses the case-insensitive function eregi to examine content with a regular expression. The code below will check that the email address entered by the user looks like an email address. If the PHP function doesn’t think it does, it’ll add our error message.

    You will need to remove the “(SPACE)” bit, as this was added due to Freeola limitations on the web forum.


    // Check for a valid email address.
    if (!eregi("^[a-z0-9]+([\.-]([a-z0-9]+))* (SPACE) @([a-z0-9]+(\.[a-z0-9]+)* (SPACE) (-([a-z0-9-]+([a-z0-9]+)))*) (SPACE) (\.[a-z]{2,4})$", $email))
    $error .= "
  • Please enter a valid email address.
  • ";


    Matching Passwords

    As explained in the previous article, users are usually asked to confirm their chosen password when signing up to a web site to ensure they’ve typed it in correctly. PHP can easily accommodate this in a similar manor to JavaScript, with a simple “Do this match that” piece of code, such as $password == $pwconfirm. The double equals sign is required to ensure the two values are compared, rather than the first taking the value of the second.

    Because we only want to alert the user if the password don’t match, we used the PHP “not equals” code, which is the same as JavaScript. If the passwords don’t match, the user is told this. However, if they do match, the password is then checked to ensure it is not less than 10 characters, using the strlen function, which counts how many characters there are.

    The code to do this is shown below, which includes the error message:


    if ($password != $pwconfirm)
    $error .= "
  • Your passwords do not match.
  • ";
    else
    $error .= (strlen($password) < 10) ? "
  • Please enter a desired password, containing 10 or more characters, and then confirm it.
  • " : "";


    There is little point in checking the length of the confirmed password, as it would have already been caught if it weren’t the same as the original password entry.

    For security reasons, it is recommended that you don’t include the users entered password within the HTML when other errors are found.

    Lickity-tick; are you firing blanks?

    Checking to see if the checkbox has been ticked and a selection has been made from the bullet point (or radio) selection list is relatively simple in PHP. Because selecting an option or ticking the box sends the value of the form control when the page is submitted, we can just check for that value, in the same way we would for a text entry form control. The full piece of code for each, including the error message, is shown below:

    Radio selection list:

    // Check the gender selection - one must be selected.
    $error .= (empty($gender)) ? "
  • Please select your gender.
  • " : "";


    Checkbox:

    // Check terms and conditions acceptance - this must be selected.
    $error .= (empty($tandc)) ? "
  • Please confirm that you agree to the terms and conditions.
  • " : "";


    The difference here is ensuing that the selections are kept if the validate, but other aspects of the form don’t. It isn’t a case of filling in the value attribute for a radio selection list or checkbox, but including the attribute checked="checked" within the correct element. This is the attribute that pre-selected a form control.

    To do this, we’ll still include some PHP within the element, but rather than just using the print value code, we’ll use similar code to the above, checking for a specific value that matches that of the form control, and printing out the checked="checked" where it is required.

    Using the checkbox as an example, the code to achieve this would be:


    … which can be read as “If the variable $tandc hold the value accepted, then the user ticked it, so include the HTML code checked="checked", so it is pre-ticked for them.”.

    The code to achieve this needs to be placed within the element, so that if the attribute is printed, it appears in the correct place.


    >


    Be sure to include a space, so that it and the previous attribute don’t sit right next to each other, so the resulting HTML is value="accepted" checked="checked" (space between attributes) and not value="accepted"checked="checked" (no space between attributes).

    With the above code, if the user ticked the checkbox, it’ll be ticked for them again if other errors are found.

    To cater to radio selection lists, you’ll need to enter similar code for each radio form control, substituting the value of the element in each case, which when using our gender example, may look like this:


    >Female
    >Male


    Because the same variable $gender is used for each radio option for this particular group of options, only the option selected by the user will be pre-selection again (unless the user didn’t select any to begin with).

    This same method can be applied to