Author: Admin 01/28/2024
Language:
PHP
Tags: php security forms
Think SECURITY when processing PHP forms! This shows how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Think SECURITY when processing PHP forms!
This shows how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).
We will name the function test_input().
Now, we can check each $_POST variable with the test_input() function, and the script looks like this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = check_input($_POST["name"]);
$email = check_input($_POST["email"]);
$website = check_input($_POST["website"]);
$comment = check_input($_POST["comment"]);
$gender = check_input($_POST["gender"]);
}
function check_input($data): string
{
$data = trim($data);
$data = strip_tags($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This maybe a bit overkill but better to be safe.