How toTech

How to apply PHP form Validation?

Apply PHP form validation: In order to achieve PHP form validation, there are a series of encounters you need to overcome. The form here is created using HTML and the validation and the processing of form contents is done using PHP. The main purpose of this article is to make you learn some different HTML forms and their validation using PHP. In this article, we will get to learn how to apply PHP form validation.

As PHP is one of those programming languages which is developed using built-in web development capabilities, the programmers can easily embed the code to HTML code through the script tag. Though the PHP programmers need to write lengthy and complex codes, the PHP frameworks reduce time. This is done by providing code generation features. The content on this page will show you how to process PHP forms with security in mind. Proper protection and validation of data are very essential to keep you from hackers and unwanted sources.

Apply PHP form validation

Before we get into the detailed explanation of PHP form validation we will go through some basic information. This basic info is in regard to the forms and also the HTML scripts and PHP.

What is a form?

A form is nothing but a document that contains blank fields where the user can fill up data. The user may also be able to select it. This data is generally stored in a database. Generally, websites provide functionalities that can use to store, update, retrieve, and delete the data in a database.

What is validation?

Validation means to check the input submitted by the user. In general, there are two types of validation available to apply PHP form validation. They are,

  1. Client-side validation This is performed on the client machine web browsers
  2. Server-side validation – After submission of the data, the data is sent to a server and a validation is performed. This validation check is done in the server machine.

Here are a set of rules for validation in PHP.

NameShould require letters and white spaces
EmailShould require @ and .
WebsiteShould require a valid URL
RadioMust be able to select at least once
Check-boxMust be able to check at least once.
Drop down menuMust be able to select at least once.

Here is a small code which shows the validation of an URL.

$website = input($_POST["site"]); 
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

Above syntax will verify whether a given URL is valid or not. It should allow some keywords as https, FTP, www, a-z, 0-9,..etc..

Below is a small code to show the validation of an email.

$email = input($_POST["email"]); 
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid format and please re-enter valid email";
}

Above syntax will verify whether the given Email address is well-formed or not.if it is not, it will show an error message.

You can send emails in PHP. Learn how to use PHP to send emails by exploring the highlighted link below this text.
How to send emails in PHP

HTML FORM

Now, let us learn some important points in regard to the HTML form. Here is an example to depict the HTML form. The purpose of the form is to capture user experience, and also to obtain feedback.

HTML form example
HTML FORM

Example: Let us go through the PHP form validation example which is depicted below.

PHP form validation example
PHP FORM VALIDATION

Here are some points in relevant to the PHP form above.

TEXT Fields

The name, email, and website fields are text input elements, and the comment field is a text area. The HTML code looks like this:

Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>

RADIO Buttons

The gender fields are radio buttons and the HTML code looks like this:

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other

The FORM Element

The overall HTML code of the FORM looks like below,

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

Any idea about the PHP preg_replace() function?. It is an expression used to perform search and also to replace the content. To know more about this function and its use in PHP explore the highlighted link below this text.
How to use prep_replace() function

Validating Form Data with PHP

To validate form data with PHP(apply PHP form validation), you need to follow some instructions. Firstly, we need to pass all the variables through PHP’s HTML specailchars() function. What happens when we use the HTML specialchars() function is that,
When the user tries to submit the following in a text field,
<script>location.href(‘http://www.hacked.com’)</script>,
this won’t be executed because this would be saved as an HTML escaped code as below,
<script>location.href(‘http://www.hacked.com’)</script>
Thereby, the code is now safe to be displayed on a page or in an email.

We also need to do two more things to validate a data form through PHP. They are,
a) Strip unnecessary characters from the user input data using the PHP trim() function.
b) Remove backlashes (\) from the user input data using the PHP stripslashes() function.

After this, we need to create a function which will do all the checking for us. Here, we will name the function test_input(). Thereby, now we can check each $_POST variable with the test_input() function. So, the script looks like this.

 <?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

On running the example, the whole set of code looks like,

<!DOCTYPE HTML>  
<html>
<head>
</head>
<body>  
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echohtmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name">
  <br><br>
  E-mail: <input type="text" name="email">
  <br><br>
  Website: <input type="text" name="website">
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <input type="radio" name="gender" value="other">Other
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";

echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

The output is as depicted below,

PHP Form validation example
PHP Form Validation example

FAQ’s

Here are some basic FAQ’s you can delve into, in order to clear up your doubts if any in regard to the topic listed in this article.

What is the $_server Php_Self variable?

PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file (from the root folder). You can use this variable in the action field of the FORM.

What does $_Request do in PHP?

$_REQUEST is a superglobal variable which is widely used to collect data after submitting HTML forms. This superglobal variable is widely used to handle form data. We will see an example where a particular PHP script is executed if after the form is submitted to another PHP script.

What is $_GET in PHP?

GET can’t be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using the QUERY_STRING environment variable. The PHP provides $_GET associative array to access all the sent information using GET method.

To conclude: Hence, through this article, we have got to learn how to apply PHP form validation using different steps and relevant examples linked up with it. If you have any queries in regard to this article comment them below in the comment section. Also, do share the content if you like it. For more of some interesting and amazing articles in regard to PHP, HTML or latest tech news visit Morphigo.com and delve into the best content in the web. Cheers!

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Related Articles

Leave a Reply

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

Back to top button
Close