I have a login script that coded in simple way. I just want to ask if this script is secured. here's the script <? function login($username,$password) { $query = mysql_query("SELECT username,password FROM table WHERE username = '$username' and password = '$password' "); if(mysql_num_rows($query) == 0) { return false; } else { return true; } } if(isset($_POST['submit'])) { $log = login($_POST['username'],$_POST['password']); if(!$log) echo "Invalid username or password"; } ?> Code (markup): What do you think guys! is the code safe from any attacks?
Definitely not secure. You need to at a minimum escape your user input. $query = mysql_query(" SELECT username,password FROM table WHERE username = '". mysql_real_escape_string($username) ."' and password = '". $password." ' "); You also should be storing your password as a hash. MD5 or SHA1. You will want to hash the password, with a salt before storing it. if(isset($_POST['submit'])) { $password = md5($_POST['password'].'NHU*E^%$SDMJN'); $log = login($_POST['username'],$password); if(!$log) echo "Invalid username or password"; }
or you can use mysql's password() function. update blah set pass = password('what they typed') where id =nn select id from users where user = 'john' and pass = password('their pass') -> to authenticate it. this way you never store any pass in plain text as well and let mysql work it out. one bit of advice - avoid naming db fields 'password' as there's a function with that name, can get confusing in big queries
Escape or sanitize any user input no matter how insignificant. Also, if you ever use hidden fields, or variables that are set by user input, anything that could possibly be altered by user input, do the same with it.