GetDotted Domains

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

The "Freeola Customer Forum" forum, which includes Retro Game Reviews, has been archived and is now read-only. You cannot post here or create a new thread or review on this forum.

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

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:


<form method="post" action="[B]<?php echo $_SERVER['PHP_SELF']; ?>[/B]">


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.

<?php represents the beginning of the PHP code, while ?> represents the end of the PHP code. Anything between <?php 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 <body> 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.


<?php [S]// Start PHP.[/S]
$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[�[B]firstname[/B]�].

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'])) { [S]// Form has been submitted.[/S]
// 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 = ��; [S]// Create empty value.[/S]
}


3:

$firstname = ��; [S]// Set variable first, as empty.[/S]

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.


[S]// Clear global variable.[/S]
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, <?php echo @stripslashes($email); ?> within the value attribute of the <input> element asking for the users email address.


Email Address:
<input type="text" name="email" value="[B]<?php echo @stripslashes($email); ?>[/B]">
<textarea name="comments">[B]<?php echo @stripslashes($comments); ?>[/B]</textarea>


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)) ? "<li>Please include your first name.</li>" : "";
$error .= (empty($lastname)) ? "<li>Please include your last name.</li>" : "";


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:


<input type="text" name="firstname" value="[U]<?php echo @stripslashes($firstname); ?>[/U]" �>
<input type="text" name="lastname" value="[U]<?php echo @stripslashes($lastname); ?>[/U]" �>


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 “[B][U](SPACE)[/U][/B]” bit, as this was added due to Freeola limitations on the web forum.


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


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 .= "<li>Your passwords do not match.</li>";
else
$error .= (strlen($password) < 10) ? "<li>Please enter a desired password, containing 10 or more characters, and then confirm it.</li>" : "";


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:

[S]// Check the gender selection - one must be selected.[/S]
$error .= (empty($gender)) ? "<li>Please select your gender.</li>" : "";


Checkbox:

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


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:
<?php echo @($tandc == "accepted") ? 'checked="checked"' : ''; ?>

… 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 <input> element, so that if the attribute is printed, it appears in the correct place.


<input type="checkbox" name="tandc" value="accepted" <?php echo @($tandc == "accepted") ? 'checked="checked"' : ''; ?>>


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:


<input � value="female"<?php echo @($gender == "female") ? ' checked="checked"' : ''; ?>>Female
<input � value="male"<?php echo @($gender == "male") ? ' checked="checked"' : ''; ?>>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 <select> form controls, applying the code to the <option> element, but replacing “checked="checked"” for “selected=�selected�”.

Just because it isn’t required, don’t mean it should be forgotten

You won’t always require a user to fill in every form element you provide. For example, you may offer the chance for them to enter their phone number, home address, job title, etc so that you can use such data for marketing, but you might not consider it a requirement. Asking for too much information, especially personal information can deter users from signing up to your site, so ensure you only require the bare essentials.

That being said, a user may choose to fill in these details anyway, but might still make a mistake with the email format, or with their password entry. Such an error would still cause the form

In our example, the comments aren’t a requirement, but if the user does enter some comments, but forget their last name and submits, the form will still retain the entered comments.

So, it’s valid?

When the code gets to the end of the end of the validation segment, we need to check if the $error variable has been populated with any error messages. We can do this with the empty function, and if the variable is empty, validation has passed.


[S]// Check error message variable.
// If it is still empty, it means no errors were found.[/S]
if (empty($error)) {
[S]// Validation passed.
// Here, you do whatever you wanted to do with your data.[/S]
echo "<p>Thank you $firstname $lastname for your submission.</p>";
$showform = FALSE; // Don't show the HTML web form.
}


We can then print out to the user a thank you that includes there name. We then also set the $showform variable to FALSE, so that the HTML web form is now not to be shown.

Where the thank you is written, is where you take over, depending on what you want to do with the users data.

Print the error, oh yeah, and the web form too!

The HTML code for the web form will be enclosed with an if statement, which checks if the form should be displayed or not. To make the code easier to read, we can jump out of PHP mode, from this point, and only jump back in and out as needed.

opening HTML code goes here

<?php
// Form validation goes here.

if ($showform) {
// error code
?>

HTML We form code goes here

<?php } ?>

Closing HTML goes here

As mentioned above, the variable $error will contain all the error messages that are created when form control validation fails. We could just use the code echo $error; to display any errors, because if the variable was empty, nothing would be seen.

However, as we’ve built our error message as an HTML list, we’ll want to check that it isn’t empty first, before we print the HTML code to start off our list. We won’t want to print such code if there is not error messages to fill it.


if (!empty($error))
echo "<ul id=\"error\">$error</ul>";


This code should be placed under the initial if ($showform) { (where it says “// error code”), so that it appears at the top of the page, above the HTML web form.

It’s all yours

You can have a look at the example form online, as well as the full source code. I’ve included some extra formatting to make the HTML appear neater. A \n includes a line break, and a \t includes a tab within the source code. It isn’t required, however.

Now that you have some idea of how to use a little PHP to include basic server-side validation, complimented with some client-side validation, your HTML web forms can now be used to cater to all sorts of tasks, such as a sign-up page, log-in form, comment form, etc.

The layout used in our example probably isn’t the prettiest way to present the user, so consider this when putting your page together. The error messages are coded using valid HTML mark-up, so you can use CSS to alter the look relatively easily.

If you’re feeling adventurous, you can alter the final layout entirely how you would like it. You don’t have to have the error message appear as a group at the top of the page, instead you could have each message appear above or below its respected form field.

You can also alter the way correctly filled in fields are presented. Rather than simply having the field filled in with the information the user entered, you could instead not have a form field, but just the text, or hide the block entirely, only offering the form fields that were incorrectly filled out.

However you choose to present your web form and validation warning, PHP offers a vast range of built-in functions, which you can view online via the official PHP documentation pages.


= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

As always, any comments, questions, and especially corrections are welcome.
Tue 13/02/07 at 00:06
Regular
"It goes so quickly"
Posts: 4,083
UPDATE: Added the PHP function stripslashes to the code that prints the already entered data back in to the <input> and <textarea> elements.
Sun 11/02/07 at 23:41
Regular
"It goes so quickly"
Posts: 4,083
[B][U]Basic validation of your HTML web form, server-side, using PHP[/U][/B]

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:


<form method="post" action="[B]<?php echo $_SERVER['PHP_SELF']; ?>[/B]">


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.

<?php represents the beginning of the PHP code, while ?> represents the end of the PHP code. Anything between <?php 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 <body> 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.


<?php [S]// Start PHP.[/S]
$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[�[B]firstname[/B]�].

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'])) { [S]// Form has been submitted.[/S]
// 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 = ��; [S]// Create empty value.[/S]
}


3:

$firstname = ��; [S]// Set variable first, as empty.[/S]

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.


[S]// Clear global variable.[/S]
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, <?php echo @stripslashes($email); ?> within the value attribute of the <input> element asking for the users email address.


Email Address:
<input type="text" name="email" value="[B]<?php echo @stripslashes($email); ?>[/B]">
<textarea name="comments">[B]<?php echo @stripslashes($comments); ?>[/B]</textarea>


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)) ? "<li>Please include your first name.</li>" : "";
$error .= (empty($lastname)) ? "<li>Please include your last name.</li>" : "";


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:


<input type="text" name="firstname" value="[U]<?php echo @stripslashes($firstname); ?>[/U]" �>
<input type="text" name="lastname" value="[U]<?php echo @stripslashes($lastname); ?>[/U]" �>


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 “[B][U](SPACE)[/U][/B]” bit, as this was added due to Freeola limitations on the web forum.


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


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 .= "<li>Your passwords do not match.</li>";
else
$error .= (strlen($password) < 10) ? "<li>Please enter a desired password, containing 10 or more characters, and then confirm it.</li>" : "";


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:

[S]// Check the gender selection - one must be selected.[/S]
$error .= (empty($gender)) ? "<li>Please select your gender.</li>" : "";


Checkbox:

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


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:
<?php echo @($tandc == "accepted") ? 'checked="checked"' : ''; ?>

… 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 <input> element, so that if the attribute is printed, it appears in the correct place.


<input type="checkbox" name="tandc" value="accepted" <?php echo @($tandc == "accepted") ? 'checked="checked"' : ''; ?>>


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:


<input � value="female"<?php echo @($gender == "female") ? ' checked="checked"' : ''; ?>>Female
<input � value="male"<?php echo @($gender == "male") ? ' checked="checked"' : ''; ?>>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 <select> form controls, applying the code to the <option> element, but replacing “checked="checked"” for “selected=�selected�”.

Just because it isn’t required, don’t mean it should be forgotten

You won’t always require a user to fill in every form element you provide. For example, you may offer the chance for them to enter their phone number, home address, job title, etc so that you can use such data for marketing, but you might not consider it a requirement. Asking for too much information, especially personal information can deter users from signing up to your site, so ensure you only require the bare essentials.

That being said, a user may choose to fill in these details anyway, but might still make a mistake with the email format, or with their password entry. Such an error would still cause the form

In our example, the comments aren’t a requirement, but if the user does enter some comments, but forget their last name and submits, the form will still retain the entered comments.

So, it’s valid?

When the code gets to the end of the end of the validation segment, we need to check if the $error variable has been populated with any error messages. We can do this with the empty function, and if the variable is empty, validation has passed.


[S]// Check error message variable.
// If it is still empty, it means no errors were found.[/S]
if (empty($error)) {
[S]// Validation passed.
// Here, you do whatever you wanted to do with your data.[/S]
echo "<p>Thank you $firstname $lastname for your submission.</p>";
$showform = FALSE; // Don't show the HTML web form.
}


We can then print out to the user a thank you that includes there name. We then also set the $showform variable to FALSE, so that the HTML web form is now not to be shown.

Where the thank you is written, is where you take over, depending on what you want to do with the users data.

Print the error, oh yeah, and the web form too!

The HTML code for the web form will be enclosed with an if statement, which checks if the form should be displayed or not. To make the code easier to read, we can jump out of PHP mode, from this point, and only jump back in and out as needed.

opening HTML code goes here

<?php
// Form validation goes here.

if ($showform) {
// error code
?>

HTML We form code goes here

<?php } ?>

Closing HTML goes here

As mentioned above, the variable $error will contain all the error messages that are created when form control validation fails. We could just use the code echo $error; to display any errors, because if the variable was empty, nothing would be seen.

However, as we’ve built our error message as an HTML list, we’ll want to check that it isn’t empty first, before we print the HTML code to start off our list. We won’t want to print such code if there is not error messages to fill it.


if (!empty($error))
echo "<ul id=\"error\">$error</ul>";


This code should be placed under the initial if ($showform) { (where it says “// error code”), so that it appears at the top of the page, above the HTML web form.

It’s all yours

You can have a look at the example form online, as well as the full source code. I’ve included some extra formatting to make the HTML appear neater. A \n includes a line break, and a \t includes a tab within the source code. It isn’t required, however.

Now that you have some idea of how to use a little PHP to include basic server-side validation, complimented with some client-side validation, your HTML web forms can now be used to cater to all sorts of tasks, such as a sign-up page, log-in form, comment form, etc.

The layout used in our example probably isn’t the prettiest way to present the user, so consider this when putting your page together. The error messages are coded using valid HTML mark-up, so you can use CSS to alter the look relatively easily.

If you’re feeling adventurous, you can alter the final layout entirely how you would like it. You don’t have to have the error message appear as a group at the top of the page, instead you could have each message appear above or below its respected form field.

You can also alter the way correctly filled in fields are presented. Rather than simply having the field filled in with the information the user entered, you could instead not have a form field, but just the text, or hide the block entirely, only offering the form fields that were incorrectly filled out.

However you choose to present your web form and validation warning, PHP offers a vast range of built-in functions, which you can view online via the official PHP documentation pages.


= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

As always, any comments, questions, and especially corrections are welcome.

Freeola & GetDotted are rated 5 Stars

Check out some of our customer reviews below:

Thank you very much for your help!
Top service for free - excellent - thank you very much for your help.
Wonderful...
... and so easy-to-use even for a technophobe like me. I had my website up in a couple of hours. Thank you.
Vivien

View More Reviews

Need some help? Give us a call on 01376 55 60 60

Go to Support Centre
Feedback Close Feedback

It appears you are using an old browser, as such, some parts of the Freeola and Getdotted site will not work as intended. Using the latest version of your browser, or another browser such as Google Chrome, Mozilla Firefox, or Opera will provide a better, safer browsing experience for you.