I've a simple registration form on my localhost (still testing), and I am wondering if it can be attacked by SQL injection?
Code:
$name = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['password']);
$password = md5($password);
$email = mysql_real_escape_string($_POST['email']);
$refId = $_GET['refid'];
$ip = $_SERVER['REMOTE_ADDR'];
$add = mysql_query("INSERT INTO `users` (`name`, `password`, `email`, `refId`, `ip`)
VALUES('$name','$password','$email','$refId', '$ip')") or die(mysql_error());
Is that safe or can someone use SQL injection (I'd like to know how)? How can I avoid injection?
The best way to avoid injections is to use Prepared Statements .
For prepared Statements I prefer to use PDO to handle all my DB stuff. here is some PDO sample code I wrote to retrieve some basic login information:
$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");
$user=$_POST[user];
$query="select Salt,Passwd from User
where Name=:user";
$stmt=$sql->prepare($query);
$stmt->bindParam(':user',$user);
$stmt->execute();
$dr=$stmt->fetch();
$sql=null;
$password=$_POST[pass];
$salt=$dr['Salt'];
... etc
Read this page for more information on PDO. If you want to know what each line of code here is doing, read this answer I gave to another post.
It is indeed vulnerable; you haven't escaped $_GET['refid']
. Take this URL for example:
yourpage.php?refid='%2C'')%3B%20DROP%20TABLE%20users%3B--
Avoiding SQL injection is easy. Use prepared statements and PDO. For example:
$query = $dbh->prepare("INSERT INTO `users`(`name`, `password`, `email`, `refId`, `ip`)
VALUES(:name, :password, :email, :refId, :ip)");
$query->bindValue(':name', $_POST['name']);
$query->bindValue(':password', md5($_POST['password'])); # Do not use MD5 for password hashing, and especially not without salt.
$query->bindValue(':email', $_POST['email']);
$query->bindValue(':refid', $_GET['refid']);
$query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
$query->execute();
You didn't mysql_real_escape_string
the $refId
, even though that's grabbed from $_GET
. That basically makes all your other injection prevention measures moot. On a tangent, if you escape string the password before md5-ing, it changes the hash.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.