I have just started PHP and mySQL and need to know if this is “safe”. The login information is passed into the following PHP file through AJAX (jQuery).
jQuery AJAX
$("#login_form").submit(function(){
$.post("login.php",{user:$('#username').val(),pass:$('#password').val()} ,function(data)
PHP
ob_start();
mysql_connect("-", "-", "-") or die("ERROR. Could not connect to Database.");
mysql_select_db("-")or die("ERROR. Could not select Database.");
//Get Username and Password, md5 the password then protect from injection.
$pass = md5($pass);
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
//See if the Username exists.
$user_result=mysql_query("SELECT * FROM users WHERE username='$user'");
$user_count=mysql_num_rows($user_result);
if($user_count==1){
if($pass_length==0){ echo "userVALID"; }
else{
$pass_result=mysql_query("SELECT * FROM users WHERE username='$user' and password='$pass'");
$pass_count=mysql_num_rows($pass_result);
if($pass_count==1){
session_register("user");
session_register("pass");
echo "passVALID";
}
else { echo "passERROR"; }
}
}
else { echo "userERROR"; }
ob_end_flush();
I know this may not be the best way to do things but, it is the way I know! I just want to know if it has any major security flaws. It is more of a concept for me and therefore I am not incorporating SSL.
You should make this change just in case people have a backslash in their password:
First and foremost md5 is very bad. Also
md5()andmysql_real_escape_string()is redundant. Collisions have been generated in the wild.sha1()although weakened is still much more secure and no collisions have been generated (yet). The best choice would be sha256 in php, or using the mhash library.You also need to salt the password.