I have a website where I use PHP in server side and mysql as database. I use the following script to retrieve data from database. Could anybody let me know whether this code is vulnerable to injection attack? If so could you please give a solution?
<?php
// PHP script
$usrname=$_POST['usrname'];
$_SESSION['usremail']=$usrname;
$usrpassword=$_POST['passwd'];
$db=mysql_select_db('mydb',$connection);
$result=mysql_query("select usrfname,usrlname from userinformation where usremail='$usrname' and usrpassword='$usrpassword'") or die('failed to login');
Any help is greatly appreciated.
Thanks
Yes, it’s vulnerable. You’re talking values directly from user input and placing it into your query.
You should look at
mysql_real_escape_string, or (preferably) use MySQLi which provides parameterised queries. SQL injections are caused by user data being injected as SQL code instead of data. The only true way to secure a query is to use parameterised queries, which separate the data and query text at the protocol level.Furthermore, your passwords are stored in plaintext. You should use a salted hash function as an absolute minimum.
You should also take a look at these awesome questions: