The strings in the input boxes can be sent with malicious contents to trigger an unwanted interaction with the database, so it is important to clean the input strings before
passing them to the database engine to prevent SQL injection.
The following PHP code sample uses the inbuilt functions stripslashes and mysql_real_escape_string to ensure the values in the $_POST array can't inject SQL queries into MySQL or similar database system.
<?php
$username = "root";
$password = "test123";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username,$password)
or die("Could not connect");
$myusername = $_POST['user'];
$myusername = $_POST['pass'];
//prevent my_sql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
?>
Note:
stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.
Definition and Usage:
The stripslashes() function removes backslashes added by the addslashes() function.
Tip: This function can be used to clean up data retrieved from a database or from an HTML form.
0 Comment to "Preventing SQL Injection using PHP"
Post a Comment