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.
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’Conner, Georges St–Pierre 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
- PHP Tutorial – a Beginner’s Basic PHP Guide Part 1
- PHP Tutorial – a Beginner’s Basic PHP Guide Part 2
- HTML Tutorial – Learn HTML in One Day – for Beginners
- CSS Tutorial – a Beginner’s CSS Guide Part 1
- CSS Tutorial – Advance user’s CSS guide Part 2
- CSS3 Selectors Cheat Sheet
You can download the files used in this article from link below
- Validate_Form_with_PHP_example_files.zip (Password: w3epic.com)
Need further help? Just leave a comment, I’ll be back to you.
Thank you!
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.
Hi abhishek,
You’re welcome… I’m glad that you found this helpful 🙂
pls i need little asistance from u
How can I help you?
So how would one go about doing this validation with a multiple selection list ()? Other than that, this has been most helpful.
Hi Jon,
Thanks for your suggestion. I’ll update the post with multiple selection list validation ASAP…
Hello again Jon, hello everyone,
The post has been updated with multiple selection list.
HI ,,,
THIS IS RAISUDDIN KHAN
I REALLY LEARNT VERY MUCH WITH THE HELP OF THIS WEBSITE
THANKS
Hello Arpan,
I can’t open the zip files, the password doesn’t work.
Is there a demo to see this script working?
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.
Strange, the same as above. But it works now!
Thank you Arpan.
how i cheked the email id if its is in my database or not?
Hi sia,
To check if only email exist or not, you can try the code below.
To check for both username and email exist or not, try the code below.
Hope this is what you want.
this article is really helpful….Nice tutorial
i found some relevant information here also so would like to share
http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/
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
Hi Dare,
Thanks for noticing this issue.
I’ve updated this article.
Now you can use names like O’neal, Jean-pierre, etc.
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:
Your code is missing or messed up as I cant see it here.
BTW, you can see this tutorial for client side form validation -> http://w3epic.com/how-to-handling-and-validating-html-forms-in-javascript-tutorial/
Post your code within <pre>[…]</pre> tag.
how to insert video using frame tag? Please tell me
Hi Nadimuthu,
You can do as the following:
frameset.html
frame1.html
frame2.html
How do I validate a file upload? Eg. uploading a resume in doc, docx and pdf format only.
Hello Rlm Au,
Please see this post: http://w3epic.com/how-to-upload-and-validate-files-using-php/
I specially wrote this for you 🙂
You are a rockstar!!!
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
.
Hello Rabia,
Have you tried this: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket ?
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.
Yes, I’ll check that for you.
Please give me some time.
Thanks.
Hello,
Have you check my problem?????????????
Hi,
Try this http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
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.
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
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?
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.
hey thanks alot for this help.
but i have problem that it register only male value of radio button into mysql.
please help me.
m using wamp server.
Showing the zip file is correct.Is there any other way to see the code.
Showing the zip file is corrupt.Is there any other way to see the code.
Is there a code to put the form into database
hello
how we check the status of user or admin when log in
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
You’re welcome!
Thank you very much for your awesome Post, I have visited once like i have done it 100 times!!
You’re welcome!
Need your favour Sir
Thanks alot
Thanks alot….,Can you please give code for validating username and password from oracle 10g database,if i do not have PDO installed.
Hi,
Thank you for the detailed tutorial; a job very well done.
Could you please ad reCAPTCHA v2.0 validation.
Thank you and regards,
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
This is my first time. Bro i have no words for the tremendous tutorials you giving to us. Am greatful
Thanks, Arpan.
This is really helpful.
Also, I like the example in the comment for username already exists.
Keep It Bro.
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.
Hi luis vargas,
You can download the files from here: https://drive.google.com/open?id=1CaKM5mFtl48zcqs3PORR52Xmqn2lYuNl
Thank you.