Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql_real_escape_string - login script

Tags:

html

php

I am currently upgrading code for a friends website and have encountered a problem with the login script. I'm trying to prevent SQL Injection by using mysql_real_escape_string(). mysql_escape_string() works fine but mysql_real_escape_string() doesn't. This is what I've got:

if (isset($_POST['submit']))
{
    $username = mysql_real_escape_string($_POST['username']); 
    $password = mysql_real_escape_string($_POST['password']);

    $db_link = db_connect("project");
    $query = "SELECT * FROM user WHERE username = '$username' AND password = password('$password')";
    $result = mysql_query($query) or die (mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows == 1)
    {
        RedirectToURL("home.php");
    }
    else
    {
        login_page("Invalid login! Try again");
    }   
}
else
{
    login_page("");
}
like image 784
user1798578 Avatar asked Jul 28 '26 02:07

user1798578


2 Answers

In order to use mysql_real_escape_string you have to be logged in to the database. If you are not logged in, then use mysql_escape_string.

like image 142
Lior Avatar answered Jul 30 '26 16:07

Lior


As @MichaelBerkowski said in your comment, move the mysql_real_escape_string() calls past your connection command:

if (isset($_POST['submit']))
{

    $db_link = db_connect("project");

    $username = mysql_real_escape_string($_POST['username']); 
    $password = mysql_real_escape_string($_POST['password']);

    $query = "SELECT * FROM user WHERE username = '$username' AND password = password('$password')";
    $result = mysql_query($query) or die (mysql_error());
    $numrows = mysql_num_rows($result);

    if($numrows == 1)
    {
        RedirectToURL("home.php");
    }
    else
    {
        login_page("Invalid login! Try again");
    }   
}
else
{
    login_page("");
}

The reason, as told above, is that mysql_real_escape_string() depends on your mysql connection to work

like image 42
Sergi Juanola Avatar answered Jul 30 '26 15:07

Sergi Juanola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!