Welcome again to another informative article to cover server-side form validation in PHP. As you know, we have already covered database connectivity, user registration, user login functionalities in our previous articles. In this article, I will take the registration form we created in our user registration article to apply server-side validation to it. So, let's start the article.
What is Server-Side validation:
It's a type of form validation that takes place on the server-side during a postback session. It is performed through server-side languages like PHP and ASP.Net. When the server-side validation is completed, the server's feedback or response is sent back to the client by generating a dynamic web page.
Writing PHP code to validate registration form:
- Open "registration.inc.php" to write validation code.
- Check whether all the input fields are empty using PHP Empty() function. If all input fields are empty, use the header() function to redirect the user to the same registration page along with the error.
- Now Check all the input fields one by one using the same Empty() function. If any of them is empty, redirect to the same registration page with the $_GET variable "error" using the PHP header() function.
- Apply a validation check to see whether the password and the repeat password are the same. If the two passwords don't match, transmit the error by the PHP header() function.
- Also, apply validation on email to see if it's a valid email.
Now see the working code of all the above-mentioned validations below.
<?php require "db.inc.php"; if(isset($_POST['submit'])){ $name = $_POST["name"]; $phone= $_POST["phone"]; $email = $_POST["email"]; $pass = $_POST["password"]; $re_pass = $_POST["re_pass"]; //Server side validation// if(empty($pass) && empty($name) && empty($phone) && empty($email) && empty($pass) && empty($re_pass) ){
header("location: ../register.php?error=AllInputsEmpty"); exit(); } if(empty($name)){ header("location: ../register.php?error=EmptyName"); exit(); } if(empty($phone)){ header("location: ../register.php?error=EmptyPhone"); exit(); } if(empty($email)){ header("location: ../register.php?error=EmptyEmail"); exit(); } if(empty($pass)){ header("location: ../register.php?error=EmptyPass"); exit(); } if(empty($re_pass)){ header("location: ../register.php?error=EmptyRe_pass"); exit(); } if($pass != $re_pass){ header("location: ../register.php?error=PassMatchError"); exit(); } if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ header("location: ../register.php?error=InValidEmail"); exit(); } //Server side validation ends here $query ="INSERT INTO `user`(`name`, `phone`, `email`, `pass`) VALUES ('$name',$phone,'$email','$pass');"; if(mysqli_query($conn, $query)){ echo "user registered successfully"; }else{ die("error while executing the query". mysqli_error($conn)); } }else{ die("error while submiting the form"); } mysqli_close($conn); ?>
In the above code, server-side form validation is applied on the form and proper errors are transmitted through the PHP GET method using the header() function shown in the figure below.
But this is not sufficient because non-technical users can not understand these errors. It will cause a decline in our site's user experience. So, we need to show proper error messages and alerts to the users. Now let's learn how to show proper alerts to the user on the "register.php" page.
Writing PHP code to show alerts to users:
- Open the "register.php" page and start the PHP script under the form tag.
- Create a div and style it with a Bootstrap class "alert alert-danger".
- Then inside the PHP script, check if the GET variable is set to "error" using the isset() function.
- Now Write alert messages for all form validation errors.
- If $_GET["error"]=="AllInputsEmpty", then it means all input fields are empty. So show alert to user accordingly.
- If $_GET["error"]=="InvalidEmail", then it means the email format is wrong. Show invalid email error to the user.
- Check for all other form validations and generate alerts to the user using the PHP echo statement.
Now check out the PHP code under the form tag and understand how to show alerts to users on response to the server-side validation. I have taken this form from our previous article about user registration in PHP.
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Login</title> </head> <body> <section> <!-- Bootstrap rows and columns --> <div class="row justify-content-center my-5"> <div class="col-6"> <!-- create form --> <form method="POST" action="includes/register.inc.php"> <!-- creating input fields inside html form --> <div class="mb-3"> <label class="form-label">Name</label> <input type="text" class="form-control" name="name"> </div> <div class="mb-3"> <label class="form-label">Phone no</label> <input type="text" class="form-control" name="phone" > </div> <div class="mb-3"> <label class="form-label">Email address</label> <input type="email" class="form-control" name="email"> </div> <div class="mb-3"> <label class="form-label">Password</label> <input type="password" class="form-control" name="password" > </div> <div class="mb-3"> <label class="form-label">Repeat Password</label> <input type="password" class="form-control" name="re_pass"> </div> <!-- creating submit button --> <button type="submit" class="btn btn-primary px-5" name="submit"> Submit </button> </form> <br> <!-- Generating alerts on repsonse to the server side validation--> <?php if(isset($_GET["error"])){
echo"<div class='alert alert-danger'>"; if($_GET["error"]=="AllInputsEmpty"){ echo "Warning! All input fields are Empty."; } if($_GET["error"]=="EmptyName"){ echo "Warning! Name field is Empty."; } if($_GET["error"]=="EmptyPhone"){ echo "Warning! Phone no field is Empty.."; } if($_GET["error"]=="EmptyEmail"){ echo "Warning! Email field is Empty."; } if($_GET["error"]=="EmptyPass"){ echo "Warning! Password field is Empty."; } if($_GET["error"]=="EmptyRe_pass"){ echo "Warning! Repeat Password field is Empty.."; } if($_GET["error"]=="PassMatchError"){ echo "Warning! Password and repeat password don't match."; } if($_GET["error"]=="InValidEmail"){ echo "Warning! your entered email is invalid."; } } ?> </div> </div> </div> </section> </body> </html>
Let's See the result of this code. Now users can see proper alert messages as a result of server-side form validation.
Let's end today's article here. We will meet in the next article with more informative content. I hope you liked this article. Keep reading and supporting us.
0 Comments