1

Im trying to allow users that are on the database to log in if their credentials are present, problem is, whenever I enter details into the login screen, it will always return Invalid Login Credentials, regardless of whether or not the name/password is on the database.

Here is what I'm working with:

loginSubmit.php

<?php

//begin our session
session_start();

//Check the username and password have been submitted
if(!isset( $_POST['Username'], $_POST['Password']))
{
    $message = 'Please enter a valid username and password';
}

else
{
    //Enter the valid data into the database
    $username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);

    //Encrypt the password
    $password = sha1($password);

    //Connect to the database
    $SQLusername = "root";
    $SQLpassword = "";
    $SQLhostname = "localhost"; 
    $databaseName = "jfitness";

    try
    {
        //connection to the database
        $dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword) 
          or die("Unable to connect to MySQL");
        echo "Connected to MySQL<br>";

        //select a database to work with
        $selected = mysql_select_db($databaseName, $dbhandle)
                or die("Could not select database");

        $query = "SELECT * FROM
                customers WHERE name = 
                ('$_POST[Username]' AND password = '$_POST[Password]')";

        $result = mysql_query($query) or die(mysql_error());
        $count = mysql_num_rows($result);

        if($count == 1)
        {
            $_SESSION['username'] = $username;
        }
        else
        {
            echo "Invalid Login Credentials";
        }

        if(isset($_SESSION['username']))
        {
            $username = $_SESSION['username'];
            echo "Hello " . $username;
        }

    } 
    catch(Exception $e)
    {

        $message = 'We are unable to process your request. Please try again later"';
    }


}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>

Login.php

<html> 
    <head> 
        <title>Login</title> 
    </head> 
    <body> 
        <h2>Login Here</h2> 
        <form action="loginSubmit.php" method="post"> 
            <fieldset> 
                <p> <label for="Username">Username</label> 
                    <input type="text" id="Username" name="Username" value="" maxlength="20" /> 
                </p> 
                <p> 
                    <label for="Password">Password</label> 
                    <input type="text" id="Password" name="Password" value="" maxlength="20" /> 
                </p> 
                <p> 
                    <input type="submit" value="Login" /> 
                </p> 
            </fieldset> 
        </form> 
    </body> 
</html>

AddUser

//Enter the valid data into the database
    $username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);

    //Encrypt the password
    $password = sha1($password);

    //Connect to the database
    $SQLusername = "root";
    $SQLpassword = "";
    $SQLhostname = "localhost"; 
    $databaseName = "jfitness";

    try
    {
        //connection to the database
        $dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword) 
          or die("Unable to connect to MySQL");
        echo "Connected to MySQL<br>";

        //select a database to work with
        $selected = mysql_select_db($databaseName, $dbhandle)
                or die("Could not select database");

        $sql = "INSERT INTO 
                customers (name, password)
                VALUES
                ('$_POST[Username]','$_POST[Password]')";

        if(!mysql_query($sql, $dbhandle))
        {
          die('Error: ' . mysql_error());
        }

        //Unset the form token session variable
        unset( $_SESSION['formToken'] );

        echo "1 record added";

        //close the connection
        mysql_close($dbhandle);

    } 
    catch (Exception $ex) 
    {
        if($ex->getCode() == 23000)
        {
            $message = 'Username already exists';
        }
        else
        {
            $message = 'We are unable to process your request. Please try again later"';
        }
user2757842
  • 651
  • 1
  • 11
  • 24
  • Password's been saved as `sha1` to start with? – Funk Forty Niner Nov 22 '14 at 23:25
  • Hi Fred -ii, Can you elaborate slightly please, I'm following a tutorial as I'm new to PHP – user2757842 Nov 22 '14 at 23:32
  • If the password hasn't been saved in the database using `sha1`, then you won't be able to login. – Funk Forty Niner Nov 22 '14 at 23:34
  • So, did you first save the password in your DB as `sha1`, you haven't responded to that question. – Funk Forty Niner Nov 22 '14 at 23:47
  • As far as I know fred, I did. I add my users using similar code to the above, I've updated my question with how I add my users – user2757842 Nov 23 '14 at 00:06
  • The password column is VARCHAR and the length is long enough to accomodate the hash? – Funk Forty Niner Nov 23 '14 at 00:11
  • That could have been it, I dropped the table and made the VARCHAR of 60 length for the password, it was 45 originally, unfortunately now though it has brought a new error, it will login anyone, even if they are not in the database, any idea what could be causing this behaviour? – user2757842 Nov 23 '14 at 00:23
  • 1
    It might be because of this, the way you have the brackets `SELECT * FROM customers WHERE name = ('$_POST[Username]' AND password = '$_POST[Password]')` Try changing it to `SELECT * FROM customers WHERE name = '$username' AND password = '$password'` and try removing `$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);` that could be affecting / rejecting characters. Make sure there is no white space also. – Funk Forty Niner Nov 23 '14 at 00:27
  • 1
    Also changing `if($count == 1)` to `if($count > 0)` - or replacing `$count = mysql_num_rows($result); if($count == 1) {` with `if(mysql_num_rows($result) > 0){` – Funk Forty Niner Nov 23 '14 at 00:29
  • Thank you Fred, I appreciate the time you took to help me. It must have been the way my select statement was. If you convert that into an answer I will select it as it is finally working – user2757842 Nov 23 '14 at 00:49
  • Another thing I noticed is that your hashed password isn't being stored as a hash. Change `('$_POST[Username]','$_POST[Password]')` in your Adduser page to `('$username','$password')`. I just tested that now. – Funk Forty Niner Nov 23 '14 at 00:50
  • You're very much welcome. I have posted my answer below, *cheers* – Funk Forty Niner Nov 23 '14 at 00:59

2 Answers2

4

It might be because of this, the way you have the brackets.
-Please see my notes about using prepared statements and password_hash() below.

SELECT * FROM customers  
WHERE name = ('$_POST[Username]'  
AND password = '$_POST[Password]') 

Change it to:

SELECT * FROM customers  
WHERE name = '$username'  
AND password = '$password'

and for testing purposes, try removing

$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);

that could be affecting / rejecting characters. Make sure there is no white space also.

Also changing if($count == 1) to if($count > 0)

or replacing $count = mysql_num_rows($result); if($count == 1) { with if(mysql_num_rows($result) > 0){

Your password is not being hashed
After testing your Adduser code, I noticed is that your hashed password isn't being stored as a hash.

Change ('$_POST[Username]','$_POST[Password]') in your Adduser page to ('$username','$password').

I suggest you move to mysqli with prepared statements, or PDO with prepared statements, they're much safer.

As it stands, your present code is open to SQL injection.

Here is a good site using PDO with prepared statements and password_hash().

See also:

CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

Try this mate

$query = "select * from customer where name = '" .$username ."' and password = '" .$password ."'";         
//use the SANITIZED data      

  $result = mysql_query($query);                 
  $row = mysql_fetch_assoc($result);                        
if($row) {                       
                $_SESSION['name'] = $row['name'];                              
                $_SESSION['password'] = $row['password'];                                   


    }                  
else {  //not found                      
header('Location: go back.php?error=2');                        
      }

    echo "Hello " . $username;