Freeola Home Get Dotted Domains Win Free Games Freeola Guides Freeola Customer Forum

Viewing Thread:

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

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 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 .

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:


3:


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:



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:



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 ďĒ.

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 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 .

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:


3:


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:



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:



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 ďĒ.

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

Check out some of our customer testimonials below:

...my thanks and praise to the lads who work in your customer service centre...
I have been with Freeola since I first went on line about 3 years ago, you also host my website and I have recomended you to many of my friends over the years. I would like...

View More Testimonials

Thank you to all the team, for all the service I have received in the past.
I am simply writing to say a big Thank You for the excellent free service you provide. I have been one of your customers for many years and am still amazed as I was at the ...

View More Testimonials

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

Go to Support Centre
Tell us what you think!

Live Chat is offline

Live Chat is available:
9am to 6:30pm Monday to Friday (excluding bank holidays).

01376 55 60 60

Send us a ticket.

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.