Whenever you allow your users to insert data, you are running risks of some sort: malicious code can be injected in your website to retrieve sensitive data or even damage it.
Generally speaking, forms are weak points of your applications: you want to make sure that whatever comes from a form undergoes a security routine (sanitation) that prevents any harm to your database.
A basic sanitation will escape dangerous characters like html code and quotations among others.
Sanitation has to take place BEFORE you store user’s data in your database.
Here a list of useful functions you can use to sanitise data:
- htmlentities() (and html_entity_decode() )
- addslashes() (and stripslashes() )
- AES_ENCRYPT() (and AES_DECRYPT() )
PLEASE NOTE: mysqli_real_escape_string() will only work if you are already connected to your database, as it will ask $dbc as a first parameter.
Here a simple example about how to prevent mysql injections, using data sanitising functions:
1 2 3 4 5 6 7 8 9 10 11 |
<!--an html form sample with one single input field--> <form action="#" method="post"> <p> fullname: <input type="text" name="fullname" value=""/> </p> <p> <input type="submit" value="send" name="submit"/> </p> </form> |
A very simple php sanitation example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php #formSanitation.php $dbc = mysqli_connect("localhost","root","root"); if( isset($_POST['submit']) ){ //storing form data into a variable $dangerous_data = $_POST['fullname']; //sanitising form data $safe_data = mysqli_real_escape_string($dbc, $dangerous_data); //you can now store sanitised data into your DB $q = "INSERT INTO `yourDB`.`yourTable` (`fullname`) VALUES ('$safe_data') "; //[...] and so on... }//end if submit ?> |
To achieve a higher level of security, you may want to read about prepared statements or PHP Data Objects (PDO)