Damian James
Damian James

Reputation: 11

SHA function issues

I have this php code from my login.php

if (isset($_POST['logIn'])) {
    $errmsg = "";
    $logname = mysqli_real_escape_string($dbc, trim($_POST['usernameIn']));
    $logpassword = mysqli_real_escape_string($dbc, trim($_POST['passwordIn']));

    $query = "SELECT user_id, username FROM members WHERE username = '$logname' AND password = SHA('$logpassword')";
    $data = mysqli_query($dbc, $query);

    if (mysqli_num_rows($data) == 1) {
        $row = mysqli_fetch_array($data);
        setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30)); //expires after 30 days
        setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30));
        $home = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
        header('Location: ' . $home);
    }
    else {
        $errmsg = '<p class="errormsg">Username or password is incorrect.</p>';
    }
}

And for some reason, it always ends up setting $errmsg in the else statement. I am sure that I'm entering information (username,password) that is correct and exists in the database.

I insert my values (from a signup script) using this query:

$query = "INSERT INTO members (username, password, email) VALUES ('$username', SHA('$password'), '$email')";

Anyone see the problem with this script? Thanks!

Upvotes: 1

Views: 373

Answers (2)

Justin Lucas
Justin Lucas

Reputation: 2321

I don't notice any significant errors in your code but I have a number of suggestions to help debug it:

  1. Check the username and password again. echo both of these out right before the query to ensure they still match what's in the database after they are escaped.
  2. echo the query string and run it in phpmyadmin or a shell.
  3. Make sure the values are being sent as a POST and not a GET.
  4. Change if (mysqli_num_rows($data) == 1) { to if (mysqli_num_rows($data) > 0) { in case two rows have the same username and password

Upvotes: 1

lepe
lepe

Reputation: 25200

You can also do it from PHP with:

VALUES ('$username', '".sha1($password)."', '$email')";

In that situation you don't need to use escape it.

Upvotes: 0

Related Questions