This is the part 2 of the PHP form. If you didn’t read the previous lesson, please read the previous one at first.
4. Validating form data
Now that you have learned how to retrieve form data, you need to validate it. It is necessary as because a user may add invalid or garbage data in the form. User inputted data are always suspicious. So, you need to be sure that the data are properly formatted.
There are different ways to validate form data. We’ll discuss few of those below. Consider the following form-
<form name="form1" method="POST" action="form-process.php"> <p> <label>Your Name (Required) : </label><br /> <input name="name" type="text"> </p> <p> <label>Username (at least 5 characters): </label><br /> <input name="username" type="text"> </p> <p> <input name="send" id="send" type="submit" value="Submit"> </p> </form>
In the above form, the name is required and the username is required and must be at least 5 characters long. Let’s write the processing script (form-process.php) to validate the following four conditions-
- If the submit form button has been clicked
- If the user has added his name
- If the user added username
- If the username is at least 5 characters long.
<?php // First check if the form button has been submitted if(isset($_POST[‘send’])){ if(!empty($_POST[‘name’])){ // Check if the name is empty echo $name = $_POST[‘name’]; }else{ echo “Name is missing.”; echo “<br />”; } if(!empty ($_POST[‘username’])){ // Check if the username is empty if(strlen($_POST[‘username’]) < 5 ){ // Check if the username is at least 5 characters. echo “Username must be at least 5 characters long.”; echo “<br />”; }else{ echo $name = $_POST[‘username’]; } }else{ echo “Username is missing.”; echo “<br />”; } }else{ echo “Unauthorized access to this page.”; } ?>
Explanation:
- How to check whether a user has come to this page from the form page: Any user may come to this page directly pasting the URL of this page in the browser. To prevent unauthorized access, we’ll check whether the user comes to this page clicking the form button. PHP has a built-in function isset() which can take a variable as parameter and can check whether the variable is set. In line 3, we take the submit button as variable and check whether the submit button has been clicked. Here is the code again-
if(isset($_POST[‘send’]))
If the user comes here directly the function will return false and the warning at line 19 will be displayed-
“Unauthorized access to this page.” - How to check whether user entered his name: PHP has another function named empty() that can check whether a variable is empty. We’ll check whether the name field(“name”) in the form is empty. If the user has entered his name that means the field is not empty and in this case the function empty() in line 4 will return true. We print his name in the next line. If the user didn’t enter his name, the function will return false and the else statement will be executed. Then, the message “Name is missing.” will be printed.
- How to check if the “username” field is not empty: In the same way, the “name” is checked, the username field is also checked by the empty() function in line 10.
- How to check if user has entered username which is at least 5 characters long: PHP has a function named strlen() which tells the length of a variable. In line 11, the strlen() function check whether “username” is less than 5 characters. If it is, the warning “Username must be at least 5 characters long.” will be displayed in the next line.
5. Sanitizing form data
It is easy for hackers to inject malicious code through form inputs, remove important files from server, damage your database etc. So, you need to sanitize user inputs to remove suspicious characters or to alter user inputs to usable form. There are few built-in php functions that helps to sanitize form data. These are as follows-
strip_tags():
strip_tags() removes any HTML and PHP tags from a string.
Example:
<form name="form1" method="POST" action="form-process3.php"> <p> <label>Your Comment (No HTML and PHP tags are allowed): </label><br /> <textarea name="comment" id="comment" cols="45" rows="5"></textarea> </p> <p> <input name="send" id="send" type="submit" value="Submit"> </p> </form>
Form input:
Lets add <script>alert(“Hi”);</script> in the comment box in the form and hit submit.
Output:
alert(“Hi”);
htmlspecialchars():
Consider these five special characters – ampersand (&), double quote, single quote, greater than (>), and less than (<) characters. They have special meaning to HTML. For example in the beginning of an html page, we use less than (<) and greater than (>) characters that is <html>. Problem is, hackers can also pass malicious scripts embedded in <script> tags through form inputs. So, what you’ll do to protect this? Well, you can convert those special characters to their equivalent HTML entities. After converting, “less than character” (<) becomes < The following table shows the special HTML characters and their equivalent entities-
Special Characters | Equivalent Entities |
&(ampersand) | & |
“(double quote) | " |
‘(single quote) | ' |
<(less than) | < |
>(greater than) | > |
Example:
<form name="form1" method="POST" action="form-process4.php"> <p> <label>Your Comment : </label><br /> <textarea name="comment" id="comment" cols="45" rows="5"></textarea> </p> <p> <input name="send" id="send" type="submit" value="Submit"> </p> </form>
And, here is the form processing script (form-process4.php)
<?php // First check whether the form has been submitted if(isset($_POST['send'])){ $comment=htmlspecialchars($_POST['comment']); echo $comment; }else{ echo "Unauthorized access to this page."; } ?>
Form input:
Lets add <script>alert(“Hi”);</script> in the comment box in the form and hit submit.
Output:
<script>alert(“Hi”);</script>
Explanation:
If you see the source of the output page(form-process4.php), you’ll see the following
<script>alert("Hi");</script>
See that the HTML special characters are converted to their equivalent html entities. In this format, the code <script> has no power to do any harm.
On the other hand, if we didn’t use the htmlspecialchars() function, you’ll see a popup message says-“hi”. And, the source of the page would be-
<script>alert(“Hi”);</script>
htmlentities():
Other than the above 5 special characters, there are more characters in HTML. htmlentities() function converts all applicable characters to HTML entities.
strip_tags(): This function removes all the HTML and PHP tags from a string. So, if the users try to add any HTML or PHP tags in a form field where it is not allowed, you can remove those tags by using this function.
Example:
<form name="form1" method="POST" action="form-process5.php"> <p> <label><strong>Your Comment : </strong></label><br /> Note: HTML and PHP tags are not allowed.<br /> <textarea name="comment" id="comment" cols="45" rows="5"></textarea> </p> <p> <input name="send" id="send" type="submit" value="Submit"> </p> </form>
And, here is the form processing script (form-process5.php)
<?php // First check whether the form has been submitted if(isset($_POST['send'])){ $comment=strip_tags($_POST['comment']); echo $comment; }else{ echo "Unauthorized access to this page."; } ?>
Form input:
Lets add “HTML body starts with <body> and end with </body>” in the comment box in the form and hit submit.
Output:
HTML body starts with and end with
mysql_real_escape_string():
When interacting user inputs with the database, you need to escape it properly (to learn more about the escaping characters, click here) to play safely. mysql_real_escape_string() function helps to escaping any problematic characters.
Example:
<form name="form1" method="POST" action="form-process6.php"> <p> <label>Username : </label><br /> <input type="text" name="Username" id="Username"> </p> <p> <label>Password : </label><br /> <input type="password" name="Password" id="Password"> </p> <p> <input name="send" id="send" type="submit" value="Submit"> </p> </form>
And, here is the form processing script (form-process6.php)
<?php $connect=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("test",$connect); // First check whether the form has been submitted if(isset($_POST['send'])){ $Username=$_POST['Username']; $Password=$_POST['Password']; //$Username=mysql_real_escape_string($_POST['Username']); //$Password=mysql_real_escape_string($_POST['Password']); $query = "SELECT * FROM users WHERE Username='$Username' AND Password='$Password'"; $result = mysql_query($query); echo $query . "<br />"; if(mysql_num_rows($result) !=0) echo "Access Granted."; else echo "Access Denied."; }else{ echo "Unauthorized access to this page."; } ?>
Form input:
Let’s assume we have a database named “test” that has a table named “users”. Table user has two columns – “Username” and “Password”. The table has one sample data (“admin” as username and “123456” as password). Now, let’s add “anyname”(without double quote) as username field and “’ OR ” = ‘”(without double quote) as password field in the form.
Output:
SELECT * FROM users WHERE Username=’anyname’ AND Password=” OR ” = ”
Access Granted.
Explanation:
Though the Username and Password is not matched with the database information the query return a match, grant access. Please look at the query string in the Output. The last part (OR ‘’=’’) of the query satisfy the condition, hence, found a match.
Now, if we escape the user inputs, this wouldn’t be happened. mysql_real_escape_string() function escaping a quotation mark by adding a backslash in front of it. Now, uncomment line 9 and 10, and run the rum again. If you add the previous inputs, the output will be as follows-
Output:
SELECT * FROM users WHERE Username=’anyname’ AND Password=’\’ OR \’\’ = \”
Access Denied.
Next Lesson: PHP Forms – Part3 ›› |