0

My current login form doesn't work correctly. It always logs me in no matter what is entered into the login form. Since the first question, I decided to change my code up lots.

Here is the up to date code:

<?php
    session_start();
    include_once("db_connect.php");

    if(isset($_POST['loginSub'])) {
        //Connect to DB
        include_once("db_connect.php");

        //Gets whatever is inside input box and prevents sql injection
        $username=($_POST['user']);
        $password=($_POST['password']);

        $query = "SELECT * FROM user WHERE user= 'kent' AND password = 'password'";
        $rows = mysqli_query($conn, $query);

        if ($rows->num_rows == 1) {
            $_SESSION['user']=$username; // Initializing Session
            header("location: loginAuth.php"); // Redirecting To Other Page
        } else {
            $error = "Username or Password is invalid!!!!";
        }
            mysql_close($conn); // Closing Connection

    }       

?>

Here is the HTML form:

<form id="login" method="POST" action="loginAuth.php">

                    <label for="user"><strong>Login:</strong></label>
                    <input type="text"size=20 autocorrect=off autocapitalize=words name="user">
                    <!--<label for="loginPassword" name="password"> <strong>Password:</strong></label>
                    <input type="password" name="Password"> -->

                    <label for="password" > <strong>Password:</strong></label> 
                    <input type="password" name="password">

                    <input name="loginSub" type="submit" value="login"> 
                </form>  

The form action loginAuth.php basically takes you to the editor page and has no php in it yet.

Each snippet of code comes from the same php page. My question is, how can I make it so it doesn't log you in when the credentials are incorrect?

Kent Godfrey
  • 73
  • 1
  • 3
  • 10

5 Answers5

2

mysqli_real_escape_string requires an connection parameter, else it will be blank:

$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);

Since, both variables are blank, your query will automatically evaluates to true.


Also, you won't need quotes for mysqli_query:

$query = mysqli_query($db,$sql);

You would also need to specify the form method which is POST:

<form id="login" method="POST" action="loginAuth.php">

This is because you are getting the data in PHP as $_POST:

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

$username=strip_tags($_POST['user']);
$password=strip_tags($_POST['password']);

Just a tip: You shouldn't store users' passwords as plain-text, you should hash/ crypt it.

In PHP 5.5, there's a Password Hash function: http://php.net/manual/en/ref.password.php.


Updated Logic:

$sql = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$query = mysqli_query($db, $sql);
$result = mysqli_result($query);

if(mysqli_num_rows($result) > 0) {
    $_SESSION['username']= $username;
    $_SESSION['id']= $id;
    //useless code doesnt work header('Location: editor.php');

// { other code }
Panda
  • 6,824
  • 6
  • 34
  • 49
  • So. something like this? $username= mysqli_real_escape_string($con, $_POST['user']); – Kent Godfrey May 16 '16 at 10:33
  • Oh, so you did, my bad. I will try to implement this and get back to you asap. Thanks in advance for your time – Kent Godfrey May 16 '16 at 10:34
  • @KentGodfrey Isn't your connection parameter `$db` as your code is :`mysqli_query("$db,$sql")` – Panda May 16 '16 at 10:35
  • 1
    Good summary of issues, but the password issue is more than just a tip and should be totally shouted out, loud and clear that plain text passwords are absolutely not the way to go! Anyhow, +1 – Martin May 16 '16 at 11:25
  • Ok, just to clear things up about the password issue, this project is a hobby and I do not plan on distributing this. I am just using it to learn SQL. I understand that I should be using some form of encryption such as hash or MD5 etc. Going back to my issue, I have implemented these answers and now I cannot navigate to the login.php page. I'm troubleshooting it now. I assume I have made a syntax error. Thanks – Kent Godfrey May 16 '16 at 12:38
  • Ok, I have fixed the error with the white screen, but I with all the answers I have been given, it is still logging me in whenever it wants. I think that there is a serious issue with my logic and i just cant identify it. Or it could be the first point you mentioned in your answer. It is automatically true... therefore it is logging me in all the time! I have implemented your code with my own connect variable ($conn) and it still isnt working. – Kent Godfrey May 16 '16 at 13:04
  • @KentGodfrey I've updated my answer with a new logic – Panda May 16 '16 at 13:08
  • So just replace that my if with that. I replaced my if statement with the one you provided and I got a white screen when trying to navigate to the page. Maybe a syntax error again :( – Kent Godfrey May 16 '16 at 13:25
  • @KentGodfrey Can you update your question with the new code? Thanks – Panda May 16 '16 at 13:26
  • Updated. Since I couldnt get it working with the answers that have been given to me, I changed things up but i still have the same problem. I implemented as many of the answers as I could – Kent Godfrey May 16 '16 at 14:39
  • @KentGodfrey It seems correct, any specific errors you are receiving? – Panda May 16 '16 at 14:43
  • @luweiqi no errors, but its just not doing what its job. It keeps letting any old piece infomation login, and access the editor.php page. It really is baffling! I appreciate your help though. – Kent Godfrey May 16 '16 at 15:18
1

Your first mistake is you haven specify form method when you not specify from method it should always $_GET but you are checking with $_POST so first please specify form method and this your login page so my advice set post method in form tag for security purpose.

<form id="login" action="loginAuth.php" method="post">

Then try may it helps you.

Denis Bhojvani
  • 819
  • 1
  • 9
  • 18
1

To summarize other answers and improve code:

In your form you need to set the method. So <form id="login" action="loginAuth.php"> becomes <form id="login" action="loginAuth.php" method="post">

To improve your form HTML:

<div id="loginform">
   <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <label for="username"><strong>Username:</strong></label>
        <input type="text" size=20 autocorrect="off" autocapitalize="words" name="username" id="username">

         <label for="password" name="password"><strong>Password:</strong></label>
         <input type="password" name="password" id="password">

         <input name="loginSub" type="submit" value="login"> 
   </form> 
</div>

Note in order to make the labels clickable the for attribute needs to match the id attribute of the input. Als the name attribute needs to match the name of the $_POST. Both of these weren't correct in your form.

To shorten your code and make it more maintainable just use the following:

First instead of if(isset($_POST['loginSub'])) { you can also just say if( $_POST ) This makes sure the rest of the code is only executed when the page is posted.

To shorten your code even more instead of doing all the sql injection prevention on seperate lines you can combine them into one. This makes maintaining a lot easier.

$username = mysqli_real_escape_string($db, stripslashes( strip_tags( $_POST['username'] ) ) );
$password = mysqli_real_escape_string($db, stripslashes( strip_tags( $_POST['password'] ) ) );

Also don't forget to add the database connection to mysqli_real_escape_string().

To see if the username and password combination match use

$sql = "SELECT * FROM `users` WHERE `username`= '$username' AND `password` = '$password' LIMIT 1";

Note the backticks around each column name. The backticks are there to prevent an error called mysql reserved words. Altough the columns names aren't reserved word but in general it's good practice to use them.

To execute the query you don't need the quotes. So $query = mysqli_query("$db,$sql"); becomes $query = mysqli_query($db, $sql);

After that you can simply do:

$query = mysqli_query($db, $sql);

if( $query ) {
  if( mysqli_num_rows( $query ) >= 1 ) {
        $_SESSION['username'] = base64_encode( $username ); 
        header('Location: home.php');
        exit(); // To prevent further exection of code
  } else {
        echo "Incorrect details.Try again!";
  }
} else {
  echo "Error in query";      
}

base64_encode makes it harder to read a session. Use base64_decode() to read it

Notice that you shouldn't be storing passwords in plain text use a function like password_hash() and password_verify().

You also shouldn't just use md5() as it is easily cracked. What you can do is use in in combination. Something like below. These are just 2 example of what you could do, I'm not saying one is better than the other. Just don't use md5() on it's own.

$password = password_hash( md5( $password) );
$password = password_hash( hash('sha512', sha1( md5( $password ) ) );
SuperDJ
  • 6,224
  • 7
  • 36
  • 62
  • Thanks for the time and effort put into this answer. I'am still working on getting it functioning correctly. Should I replace the if statement i have for the if statement you have given me? – Kent Godfrey May 16 '16 at 12:56
  • @KentGodfrey Which if statement do you mean? You can just try it out which one suits your needs – SuperDJ May 16 '16 at 13:25
  • I have updated my question with new improved coding. Easier to read and it should do the job... It took some logic from your if statement. Still allows any tom,dick or harry to access it . – Kent Godfrey May 16 '16 at 16:01
0

First of all the query should be checking both the username and password. It should be like this:

$sql = "SELECT * FROM users WHERE username = '$username' and password = '$password'";

Then check the results to see if you're not getting any records, then show a message like "invalid credentials". If not you should redirect or show what part you want to.

Bono
  • 4,477
  • 6
  • 43
  • 76
  • Please note that this solution is vulnerable to [sql injection](http://stackoverflow.com/questions/601300/what-is-sql-injection). – Bono May 16 '16 at 11:37
0

Some quick fixes for you could be:

1) Specify method to form method="POST"

2) mysqli_real_escape_string expects two parameters. Please check this link for more information. Change the following code from

$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);

to

$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);

3) Change $query = mysqli_query("$db, $sql"); to $query = mysqli_query($db, $sql);

4) Also check for the updated query for checking username and password.

<?php
    session_start();
    include_once("db_connect.php");

    if(isset($_POST['loginSub'])) 
    {
        //Connect to DB
        include_once("db_connect.php");

        //Gets whatever is inside input box and prevents sql injection
        $username = strip_tags($_POST['user']);
        $password = strip_tags($_POST['password']);

        //Gets whatever is inside input box and prevents sql injection
        $username = stripslashes($username);
        $password = stripslashes($password);

        //Gets whatever is inside input box and prevents sql injection
        $username = mysqli_real_escape_string($db, $username);
        $password = mysqli_real_escape_string($db, $password);

        // Look in users table and filter those who have same username is the one inputed.
        $sql = "SELECT id, username  FROM users WHERE username = '$username' and password = '$password' ";
        $query = mysqli_query($db, $sql);

        if($query)
        {
            if(mysqli_num_rows($query) == 1)
            {
                $_SESSION['username']= $username;
                $_SESSION['id']= $id;
                header('Location: home.php');
            }
            else
            {
                echo "Incorrect details.Try again!";
            }
        }
        else
        {
            echo "Error in query";
        }
    }   
?>


<div id="loginform">
    <form id="login" action="loginAuth.php" method="POST">
        <label for="login"><strong>Login:</strong></label>
        <input type="text"size=20 autocorrect=off autocapitalize=words name="user">
        <label for="loginPassword" name="password"> <strong>Password:</strong></label>
        <input type="password" name="Password">
        <input name="loginSub" type="submit" value="login"> 
    </form> 
</div>
Suyog
  • 2,354
  • 1
  • 10
  • 26