The organization of data security is of great importance in PHP. Let’s take a look at a few simple mechanisms that can improve the security of our website.
But first, let’s take the form from the previous topic:
<!DOCTYPE html> <html> <head> <title>Data Entry Form :: easywptutorials.com</title> <metacharset="utf-8" /> </head> <body> <?php $name = "not defined"; $age = "not defined"; if(isset($_POST["name"])){ $name = $_POST["name"]; } if(isset($_POST["age"])){ $age = $_POST["age"]; } echo "Name: $name <br> Age: $age"; ?> <h3>Data Entry Form</h3> <form method="POST"> <p>Name: <input type="text" name="name" /></p> <p>Age: <input type="number" name="age" /></p> <input type="submit" value="Submit"> </form> </body> </html>
And let’s try to enter some data into it. For example, enter in the name field “<script>alert(hi);</script>”:
After sending the data to the HTML markup, a javascript code will be injected that displays a message box.
This is a relatively simple and harmless script. However, the injected code may be more malicious. And to avoid such security issues, it is recommended to use the htmlentities() function. It takes as a parameter the value to be escaped:
$name = "not defined"; $age = "not defined"; if(isset($_POST["name"])){ $name = htmlentities($_POST["name"]); } if(isset($_POST["age"])){ $age = htmlentities($_POST["age"]); } echo "Name: $name <br> Age: $age";
And even after entering the HTML or javascript code, all tags will be escaped and we will get the following output:
Another special function – htmlspecialchars() is similar in action to htmlentities:
$name = "not defined"; $age = "not defined"; if(isset($_POST["name"])){ $name = htmlspecialchars($_POST["name"]); } if(isset($_POST["age"])){ $age = htmlspecialchars($_POST["age"]); } echo "Name: $name <br> Age: $age";
Another function – the strip_tags() function allows you to completely exclude HTML tags:
$name = "not defined"; $age = "not defined"; if(isset($_POST["name"])){ strip_tags($_POST["name"]); } if(isset($_POST["age"])){ strip_tags($_POST["age"]); } echo "Name: $name <br> Age: $age";
The result of its work with the same input will be the following output: