Forms are used to collect data from users and send it to the backend code which communicates with the database in a web application. A form starts and ends with the <form></form>
tags and it is a block element with other sub tags like <input/>
, <textarea></textarea>
,<select>
and the rest.
Let’s take a look at a simple form below.
To prevent the dangers posed by submitting data to the database using forms, we can use the following PHP functions.
htmlspecialchars()
: This will escape all HTML tags which are attached to the form. So, if a user inputs something like this,<script>location.href('http://www.badscript.com')</script>
it will be converted by the function
<script>location.href('http://www.badscript.com')</script>
.
By doing this, we can catch an attempt as an error in our code. The attack will be read as wrong input.
trim()
: This function will remove spaces, extra tabs and new lines from both ends of strings that are passed as arguments to it.
stripslashes()
: This will strip off any backslahes from our user’s input.
The MySQLi class has some methods that can perform validation, like escaping special characters.
For example, mysqli->real_escape_string()
will clean its argument.
Now, let’s validate the simple form introduced at the beginning of this shot together.
<html><body><!-- our form to be procees by the scripts here--><form style ="background-color: black; padding:2rem;"action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"method="post">Name: <input style ="margin-bottom:2rem"type="text" name="names"><br>E-mail: <input style ="margin-bottom:2rem"type="text" name="email"><br><input value ="SUBMIT" type="submit" name="submit"></form></body></html><?php// define variables and set to empty values$name = $email = "";//check what request method is sentif ($_SERVER["REQUEST_METHOD"] == "POST") {//check for the submit button clickif(isset($_POST['submit'])){//Clean our input with our cleaner function$names = input_cleaner(($_POST["names"]));$email = input_cleaner(($_POST["email"]));}//create our cleaner/validation functionfunction input_cleaner($input) {$input = trim($input);$input = stripslashes($input);$input = htmlspecialchars($input);return $input;}?>
In the sample above, ?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
was given as the value of our action attribute. This means that the form is to be processed by the script in the same file.
Notice we escaped the address using htmlspecialchars()
to avoid someone executing their scripts with our program so as to get some privileged information.
You can do more to protect your database using prepared statements. Check here on how to do so.