How to Validate Form with PHP – Server Side Validation

arp14 HTML, PHP, Tutorial Tags: , , , , 51

In this post, you’ll learn – How to Validate Forms with PHP and it will be a server side form validation. We will create a user registration form at first, and then we will validate fields of that form such as name, email, phone number, birth date, bio etc.

How to Validate Form with PHP - Server Side Validation hi res snap

What is the difference between client side form validation and server side form validation?

Client side form validation is done in user’s machine but server side form validation is done on server. We cannot relay on data that are only validated in client side because a expert level user may change those data before submission to the server. Bad data can harm a server, steal information or even can delete a whole database.

As server side form validation is done on server, the submitted data is validated and cleaned by server and then it is used. No one can modify those data without having access to the server.

Validate a HTML Form with PHP

In this example, you will need two files as below with correspondence names. Save these files and try in your local machine. These files are commented enough to understand what’s going on.

html_form_to_validate.php

<?php 
	include('validate.php');
	function selected($blood_group, $choice) {
		if($blood_group==$choice) echo "selected";
	}
?>
<html>
	<head>
	<title>Validating Form with PHP - by Arpan Das (http://w3epic.net)</title>
	<style>
		body {
			font-family: 'trebuchet ms'; 
			font-size: 1.4em;
			padding: 0 50px; color: #444;
		}
		input, textarea {font-size: 1em;}
		p.error {background: #ffd; color: red;}
		p.error:before {content: "Error: ";}
		p.success {background: #ffd; color: green;}
		p.success:before {content: "Success: ";}
		p.error, p.success {font-weight: bold;}
	</style>
	</head>
	<body>
		<h1>Validating Form with PHP - by Arpan Das (http://w3epic.net)</h1>
		<h2>Please fill up the form below and submit.</h2>
		<?=$error?>
		<form action="html_form_to_validate.php" method="post">
		<table>
			<tr>
				<td>Username: </td>
				<td><input type="text" name="username" value="<[email protected]$username?>"/> (3 to 20 alpha-numeric characters)</td>
			</tr>
			<tr>
				<td>First name: </td>
				<td><input type="text" name="first_name" value="<[email protected]$first_name?>"/> (3 to 20 alpha characters only)</td>
			</tr>
			<tr>
				<td>Last name: </td>
				<td><input type="text" name="last_name" value="<[email protected]$last_name?>"/> (3 to 20 alpha characters only)</td>
			</tr>
			<tr>
				<td>Password: </td>
				<td><input type="password" name="password" value="<[email protected]$password?>"/> (3 to 20 characters only)</td>
			</tr>
			<tr>
				<td>Confirm password: </td>
				<td><input type="password" name="confirm_password" value="<[email protected]$confirm_password?>"/> (3 to 20 characters only)</td>
			</tr>
			<tr>
				<td>Email: </td>
				<td><input type="text" name="email" value="<[email protected]$email?>"/> (Valid email like [email protected])</td>
			</tr>
			<tr>
				<td>Phone: </td>
				<td><input type="text" name="phone" value="<[email protected]$phone?>"/> (10 digit mobile number)</td>
			</tr>
			<tr>
				<td>Gender: </td>
				<td><input type="radio" name="gender" value="male" <?php if(@$gender=='male')echo 'checked="true"';?> 
												<?php if(!isset($gender))echo 'checked="true"';?>/> male 
												<input type="radio" name="gender" value="female" 
												<?php if(@$gender=='female')echo 'checked="true"';?> /> female</td>
			</tr>
			<tr>
				<td>Blood Group: </td>
				<td>
					<select name='blood_group'>
						<option value="0" >Select Blood Group</option>
						<option value="1" <?php selected(@$blood_group, 1) ?>>A Positive</option>
						<option value="2" <?php selected(@$blood_group, 2) ?>>A Negative</option>
						<option value="3" <?php selected(@$blood_group, 3) ?>>B Positive</option>
						<option value="4" <?php selected(@$blood_group, 4) ?>>B Negative</option>
						<option value="5" <?php selected(@$blood_group, 5) ?>>AB Positive</option>
						<option value="6" <?php selected(@$blood_group, 6) ?>>AB Negative</option>
						<option value="7" <?php selected(@$blood_group, 7) ?>>O Positive</option>
						<option value="8" <?php selected(@$blood_group, 8) ?>>O Negative</option>						
					</select>
				</td>
			</tr>
			<tr>
				<td>Date of Birth: </td>
				<td><input type="number" name="day" value="<[email protected]$day?>" size=2/>/
					<input type="number" name="month" value="<[email protected]$month?>" size=2/>/
					<input type="number" name="year" value="<[email protected]$year?>" size=4/> (DD/MM/YYYY)</td>
			</tr>
			<tr>
				<td>Bio: </td>
				<td><textarea name="bio"><[email protected]$bio?></textarea></td>
			</tr>
		</table>			
			<input type="submit" name="submit" value="Submit"/> <input type="reset" name="reset" value="Reset"/>
		</form>
		<?php
			if (isset($_POST['submit']) && $error == '') { // if there is no error, then process further
				echo "<p class='success'>Form has been submitted successfully.</p>"; // showing success message

				// hashing the password and sanitize data
				$_POST['password'] = md5($_POST['password']);
				foreach ($_POST as $key => $val) {
					$_POST[$key] = mysql_real_escape_string($_POST[$key]);
					// Or you can use $mysqli->real_escape_string() as above function is deprecated
					// Or you can use prepared statements to sanitize
					// Use stripslashes to do the opposite
				}

				// do stuffs with validated & safe data

				//show the raw data (for practice)
				var_dump($_POST);
			}
		?>
	</body>
</html>

validate.php

<?php
/*=============================================================*/
#### How to Validate Form with PHP - Server Side Validation ####
#### Author	: 	Arpan Das						####
#### site	: 	http://w3epic.com/							####
#### email	:	[email protected]					####
/*=============================================================*/

$error = ""; // Initialize error as blank

if (isset($_POST['submit'])) { // check if the form is submitted
	#### removing extra white spaces & escaping harmful characters ####
	$username 			= trim($_POST['username']);
	$first_name 		= trim($_POST['first_name']);
	$last_name 			= trim($_POST['last_name']);
	$password 			= $_POST['password'];
	$confirm_password 	= $_POST['confirm_password'];
	$email 				= $_POST['email'];
	$phone				= $_POST['phone'];
	$gender				= $_POST['gender'];
	$blood_group		= $_POST['blood_group'];
	// dob
		$day 			= $_POST['day'];
		$month 			= $_POST['month'];
		$year 			= $_POST['year'];
		$dob			= $day.$month.$year;
		$age 			= date("Y")-$year;
	$bio				= $_POST['bio'];

	#### start validating input data ####
	#####################################

	# Validate Username #
		// if its not alpha numeric, throw error
		if (!ctype_alnum($username)) {
			$error .= '<p class="error">Username should be alpha numeric characters only.</p>';
		}
		// if username is not 3-20 characters long, throw error
		if (strlen($username) < 3 OR strlen($username) > 20) {
			$error .= '<p class="error">Username should be within 3-20 characters long.</p>';
		}

	# Validate First Name #
		// if its not alpha numeric, throw error
		if (!ctype_alpha(str_replace(array("'", "-"), "",$first_name))) { 
			$error .= '<p class="error">First name should be alpha characters only.</p>';
		}
		// if first_name is not 3-20 characters long, throw error
		if (strlen($first_name) < 3 OR strlen($first_name) > 20) {
			$error .= '<p class="error">First name should be within 3-20 characters long.</p>';
		}

	# Validate Last Name #
		// if its not alpha numeric, throw error
		if (!ctype_alpha(str_replace(array("'", "-"), "", $last_name))) { 
			$error .= '<p class="error">Last name should be alpha characters only.</p>';
		}
		// if first_name is not 3-20 characters long, throw error
		if (strlen($last_name) < 3 OR strlen($last_name) > 20) {
			$error .= '<p class="error">Last name should be within 3-20 characters long.</p>';
		}

	# Validate Password #
		// if first_name is not 3-20 characters long, throw error
		if (strlen($password) < 3 OR strlen($password) > 20) {
			$error .= '<p class="error">Password should be within 3-20 characters long.</p>';
		}

	# Validate Confirm Password #
		// if first_name is not 3-20 characters long, throw error
		if ($confirm_password != $password) {
			$error .= '<p class="error">Confirm password mismatch.</p>';
		}

	# Validate Email #
		// if email is invalid, throw error
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // you can also use regex to do same
			$error .= '<p class="error">Enter a valid email address.</p>';
		}

	# Validate Phone #
		// if phone is invalid, throw error
		if (!ctype_digit($phone) OR strlen($phone) != 10) {
			$error .= '<p class="error">Enter a valid phone number.</p>';
		}

	# Validate Gender #
		// if gender is not selected or invalid, throw error
		if ($gender != 'male' && $gender != 'female') {
			$error .= '<p class="error">Please select your gender.</p>';
		}

	# Validate Blood Group #
		// if blood group is not selected, throw error
		if ($blood_group == 0) {
			$error .= '<p class="error">Please select your blood group.</p>';
		}

	# Validate Date of Birth (DOB) #
		// if day is not 1-31, throw error
		if (intval($day)<1 OR intval($day)>31) {
			$error .= '<p class="error">Enter a valid day between 1-31.</p>';
		}
		// if month is not 1-12, throw error
		if (intval($month)<1 OR intval($month)>12) {
			$error .= '<p class="error">Enter a valid month between 1-12.</p>';
		}
		// if age is below 18 , throw error
		if ($age < 18) {
			$error .= '<p class="error">You should be at least 18 years old.</p>';
		}

	# Validate Bio #
		if (strlen($bio)==0 OR strlen($bio)>240) {
			$error .= '<p class="error">Please write something about you withing 240 characters.</p>';
		}

	#### end validating input data ####
	#####################################
}

Explanation

html_form_to_validate.php

The core structure – representation part is placed within html_form_to_validate.php and the actual validation process is done in validate.php. We included validate.php in the beginning of html_form_to_validate.php.

In this form, we used post method. If you want, you can use get method, just change method=”get” and replace $_POST with $_GET – that’s all. We used text inputs, password inputs, number inputs, radio button inputs and a textarea input.

For each one’s value attribute, we used <[email protected]$username?>. This PHP syntax is shorthand for echoing a variable inline (see this post for more on PHP Shorthand Syntax) and “@” as prefix on any expression in PHP, any error messages that might be generated by that expression will be ignored. We used “@” in case if the variable is not set, it won’t show any error.

In the html_form_to_validate.php you can see the input conditions are written at the right side of each input field. Exactly these conditions will be validated in validate.php.

After all, sanitize is done in line 100. You can  use mysql_real_escape_string() or $mysqli->real_escape_string() or prepared statements. mysql_real_escape_string is deprecated, so I suggest you to use rest of two.

validate.php

In validate.php at very beginning, we initialized variable name $error as blank. Then rest of the script will be executed if the form is submitted as line 11. We removed extra white spaces & escaped harmful characters by trim and mysql_real_escape_string functions respectively. Remember, mysql_real_escape_string is deprecated as of PHP 5.5.0, and will be removed in the future versions. So, find an alternative.

After that, we started to validating each fields from line 30. We used ctype_alnum to check if user input is alpha-numeric or not, If not, we concatenated $error variable by “.=” with a error paragraph telling the error.

Like that, we also used ctype_alpha and ctype_digit to check alphabets and digits receptively in same way. For the first name and last name field, we used str_replace function to add “-” and “‘” as exception. So, we can put names like Brian O’ConnerGeorges StPierre etc. containing dashes and single quotes.

To check size of a user input string, we used strlen() function. To validate a range of characters, we used this piece of code

if (strlen($input) < min OR strlen($input) > max) { // throw error }

To check the confirm password is same with password, we just used

if ($confirm_password != $password) { // throw error }

To validate email address, we used filter_var. But you can also use regexp to do the same.

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // throw error }

The rest of it is same. If you need any help on PHP, HTML or CSS – see tutorials below

You can download the files used in this article from link below

Need further help? Just leave a comment, I’ll be back to you.

Thank you!

51 thoughts on “How to Validate Form with PHP – Server Side Validation

  1. Hi Arpan i actually came on your site for the first time and i found it very interesting and helpful so i would like to thanks you for creating and offering such a nice site for beginner’s like me.

    1. Hi Via,
      Sorry for trouble, the password is w3epic.com
      It has been corrected.
      Sorry, for now – there is no demo available, I’ll post one ASAP. Keep visiting!
      Thank you.

    1. Hi sia,

      To check if only email exist or not, you can try the code below.

      $result = $mysqli->query("SELECT email from users WHERE email = '[email protected]' LIMIT 1");
      if ($result->num_rows == 1) {
      	// email exists
      	echo "Email already exists!";
      } else {
      	// email does not exist, continue...
      }
      

      To check for both username and email exist or not, try the code below.

      $exists = 0;
      $result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1");
      if ($result->num_rows == 1) {
      	$exists = 1;
      	$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
      	if ($result->num_rows == 1) $exists = 2;	
      } else {
      	$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
      	if ($result->num_rows == 1) $exists = 3;
      }
      
      if ($exists == 1) echo "Username already exists!";
      else if ($exists == 2) echo "Username and Email already exists!";
      else if ($exists == 3) echo "Email already exists!";
      else {
      	# insert data into mysql database
      }
      

      Hope this is what you want.

  2. Thanks Arpan for the very useful code example, But i noticed that the validation of first name and last name will flag names like O’neal, Jean-pierre, etc as invalid which should not be

  3. Hello, first I will thank you for given out such an interesting tutorial that helped a lot of beginners, I need some help from you please, I build a website using an HTML theme that I downloaded online but I don’t know how to validate the contact form for client side and server side (using php preferably ), please see the below code of the form tag that I have with the theme contact page, thank you in advance,

    Nom:

    Email:

    Sujet:

    Message:

    1. Hi Nadimuthu,
      You can do as the following:

      frameset.html

      <!DOCTYPE html>
      <html>
      	<frameset cols="50%,50%">
      		<frame src="frame1.html">
      		<frame src="frame2.html">
      	</frameset>
      </html>
      

      frame1.html

      <video width="320" height="240" controls>
      	<source src="video1.mp4" type="video/mp4">
      </video>
      

      frame2.html

      <video width="320" height="240" controls>
      	<source src="video2.mp4" type="video/mp4">
      </video>
      
  4. Hello,
    Thanks this tutorial is very help full.
    I need your help Please.
    I am building a website in html and php using dreamweaver and xampp server .
    I want to build a chat in this website,using websockets ,I dont know how to configure web socket in local host using php.I need your help, Please Arpan help me
    .

  5. hello,
    Thanks for your reply,I check that earlier but I dont know how to configure runs all the time.Its starts only when browser is in processing state.When browser loads completely its stop or disconnected.Will you check that problem.

  6. Arpan – does this method of server side validation support displaying errors inline (beside each field where problems are discovered)? Or do all of the problem conditions need to be listed at the top of the form? I have worked with multiple web developers who have indicated that it is difficult to display validation errors inline, and I am looking for example code to recommend.

    1. Yes, errors can be made inline with the help of an array of errors for each fields correspondingly.
      I’ve showed the easiest method to keep it as simple as possible, – but you may try with array.
      Thanks

  7. Excellent tutorial, one question, is there a way of using a header location code to make it go to a “thank you” page once submitted and validated?

    1. Yes of course,
      Create a page with name thankyou.php
      Then redirect user to that page after validation.
      Use sleep function to pause the script in thank you page.
      Then redirect back to whereever you want.

  8. hello sir
    i am very thankful to give the validation in php with explanation that is very easily understandable. i am student so i have very eaisly understand the code with the help of explanation.
    thanks again

  9. Thanks alot….,Can you please give code for validating username and password from oracle 10g database,if i do not have PDO installed.

  10. Hi after trying to make a login system for about a week now and not being able to for some reason or other i came across your’s and had few problems trying to connect to the database but then i got it right and it now works so would like to say thank you for your help

  11. Hi there mate, could you re-upload the zip file. I’ve not been able to download it, it’s showing a temporarily disabled link
    Thanks for any help.

Leave a Reply

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