Search code examples
phpmysqlmysql-real-escape-string

Can not login in my site with mysql_real_escape_string


I need some help here. I have coded some kind of site with "login" system and trying to prevent SQL injections. Everything works just perfect without that escape string thingy. When I add in mysql_real_escape_string() I can not log in my site anymore and its annoying.

I got no ideas what should be wrong, had tried to google the problem but didn't find anything. So I have got a form, that sends information about user through $_POST['user'] and $_POST['pass'] into check.php. In check.php I have got code to check if user and pass equals with user and pass in MySQL DB.

<?php
include ('mysql.php'); // includes mysql connection
    if(isset($_POST['user']) && isset($_POST['pass'])) {
    $user = mysql_real_escape_string($_POST['user']);
    $pass = mysql_real_escape_string($_POST['pass']);
    $row = mysql_fetch_row(mysql_query("SELECT * FROM users WHERE username = '$user'"));

    if(($user == $row[1]) and ($pass == $row[2])) {
        setcookie("user",$user,time() + 3600,"/");
        header('location: secret.php'); 
    } else {
        header('location: index.php');
    };
};

Usernames and passwords contain only letters and numbers, and I know that I'm typing username and password correctly.


Solution

  • If usernames and passwords only contains alpha-numerics character, try to use ctype_alnum ( string $text ) so you just verify if $user and $pass are only alpha-numerics characters. If they are (if its returning true), you then dont need to sanitize them.

    By the way, you should now use mysqli_real_escape_string instead of mysql_real_escape_string ! mysql_* functions are deprecated.

    I hope it'll help

    Have a look on this similar question, that have been solved: http://forums.phpfreaks.com/topic/68338-solved-cant-login-using-mysql-real-escape-string/

    Edit: Also, Fred -ii-'s comment provided you a good method to debug your code.