PHP Form Validation
When you process PHP forms, think about SECURITY!
Here you will learn how to handle PHP forms in a way that is safe. To protect your form from hackers and spammers, it\’s important to make sure that the form data is correct.
Input fields on the HTML form we\’ll be working on in these chapters include required and optional text fields, radio buttons, and a submit button.
Required field checks to see if the field is filled out correctly. Most of the time, we\’ll use a * to indicate a required field.
What exactly is validation?
Validation means to check what the user typed in. PHP has two ways to check if something is correct. Here\’s what they are:
Client-Side Validation: Validation is done on the web browsers on the client machine.
Server-side validation: Once the data has been sent, it is sent to a server, where validation checks are done.
Some of the rules for field validation
Field | Validation Rules |
---|---|
Name | Should required letters and white-spaces |
Should required @ and . | |
Website | Should required a valid URL |
Radio | Must be selectable at least once |
Check Box | Must be checkable at least once |
Drop Down menu | Must be selectable at least once |
When the form is sent, the data is sent with method=\”post,\” which is a safe way to send information.
PHP – Validate Name
The code below shows a simple way to check if the name field only has letters, dashes, apostrophes, and spaces. If the name field\’s value isn\’t correct, save an error message:
$name = test_input($_POST[\”name\”]);
if (!preg_match(\”/^[a-zA-Z-\’ ]*$/\”,$name))
{
$nameErr = \”Only letters and white space allowed\”;
}
URL Validation
The code below shows that a URL is valid.
$website = input(\”site\”; $_POST);
if (!preg match( \”www.)
[-a-z0-9+&@#\\/%?=~_|!:,.;]
*[-a-z0-9+&@#\\/%=~ |]/i\”,$website)) $websiteErr = \”URL not valid\”;
The above code will check if a given URL is correct or not. Some keywords should be allowed, like https, ftp, www, a-z, 0-9, etc.
Email Validation
The code below shows how to check an email address.
$email = input($ POST[\”email\”]);
if (!filter var($email, FILTER VALIDATE EMAIL)) $emailErr = \”Invalid format. Please try again with a valid email address\”;
The above code will check to see if a given email address is well-formed.
If it isn\’t, an error message will appear.
What does the variable $_SERVER[\”PHP SELF\”] do?
The $_SERVER[\”PHP SELF\”] super global variable gives back the filename of the script that is currently running.
So, the $_SERVER[\”PHP SELF\”] sends the form data to the page itself instead of going to a different page. So, the error messages will be on the same page as the form.
What does the function htmlspecialchars() do?
Special characters are turned into HTML entities by the htmlspecialchars() function. This means that HTML characters like and > will be changed to and >. This stops attackers from taking advantage of the code by putting HTML or JavaScript code in forms (called \”cross-site scripting attacks\”).
Big Note on the Security of PHP Forms
Hackers can use the $_SERVER[\”PHP SELF\”] variable to do bad things!
If your page uses PHP SELF, a user can enter a slash (/) followed by Cross-Site Scripting (XSS) commands to run.
Cross-site scripting, or XSS, is a type of security hole that is often found in Web applications. With XSS, attackers can add client-side script to Web pages that other users can see.
Let\’s say we have a page called \”test form.php\” with the following form:
<form method=\”post\” action=\”<?php echo $_SERVER[\”PHP SELF\”];?>\”>
Now, if a user types \”http://www.example.com/form.php\” into the address bar, the above code will be turned into:
<form method=\”post\” action=\”form.php\”>
But imagine that a user types http://www.coderazaa.com/form.php/%22%3E%3Cscript%3Ealert(\’coderazaa\’) into the address bar.
In this case, the above code will be turned into:
<form method=\”post\” action=\”form.php\”>
<script>alert(\’coderazaa\’)</script>
A script tag and an alert command are added by this code. And the JavaScript code will be run when the page loads (the user will see an alert box). This is just a simple example of how the PHP SELF variable can be used in a harmless way.
Be aware that the script> tag can contain any JavaScript code. A hacker can send the user to a file on another server. That file can contain malicious code that can, for example, change the global variables or send the form to another address to save the user\’s data.
How to Keep $_SERVER[\”PHP SELF\”] Attacks from Happening?
By using the htmlspecialchars() function, you can avoid exploits that use $_SERVER[\”PHP SELF\”].
The code for the form should look like this:
<form method=\”post\” action=\”<?php echo htmlspecialchars($_SERVER[\”PHP_SELF\”]);?>\”>
Special characters are turned into HTML entities by the htmlspecialchars() function. Now, if the user tries to take advantage of the PHP SELF variable, the following message will be shown:
<form method=\”post\” action=\”form.php/"><script>alert(\’coderazaa\’)</script>\”>
The attempt to exploit fails, and nothing bad happens!
Validate Form Data With PHP
PHP can be used to validate form data.
We\’ll start by running all variables through PHP\’s htmlspecialchars() function.
When we use the htmlspecialchars() function, if a user puts the following in a text field and tries to submit it, it won\’t work.
<script>location.href(\’http://www.coderazaa.com\’)
</script>
– This would not be run because it would be saved as HTML escaped code, like this:
<script>location.href(\’http://www.coderazaa.com\’)</script>
Now, it\’s safe to show the code on a page or in an email.
When the user sends in the form, we will also do two other things:
With the PHP trim() function, you can remove any extra spaces, tabs, or newlines from the user\’s input.
With the PHP stripslashes() function, you can remove backslashes () from the user\’s input data.
The next step is to make a function that checks everything for us (which is much more convenient than writing the same code over and over again).
The name of the function will be test input ().
Now, we can use the test input() function to check each $_POST variable. The script looks like this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body><?php
if ($_SERVER[\”REQUEST_METHOD\”] == \”POST\”) {
$name = test_value($_POST[\”name\”]);
$email = test_value($_POST[\”email\”]);
$website = test_value($_POST[\”website\”]);
$comment = test_value($_POST[\”comment\”]);
$gender = test_value($_POST[\”gender\”]);
}function test_value($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?><h2>PHP Validation Form</h2>
<form method=\”post\” action=\”<?php echo htmlspecialchars($_SERVER[\”PHP_SELF\”]);?>\”>
Your Name: <input type=\”text\” name=\”name\”>
<br><br>
Your 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>