1

I've got a login for a project that I'm trying to figure out. I've got a values by POST (through an AJAX call), I've already checked if the username entered exists and up to there, it works well. But know I want to check if the password is valid for that username. Here's the PHP code:

<?php

    //File with the conection data
    include_once "../conexion.php";

    //Initialization
    $user = "";
    $password = "";
    $errors = "";
    $result = "";
    $result2 = "";

    //Some validations (I've edited a little to make it shorter)
    if((isset($_POST['user'])) && (!empty($_POST['user']))){
        $user = $_POST['user'];
    }else{
        $errors .= "blablablah";
    }

    if((isset($_POST['password'])) && (!empty($_POST['password']))){
            $password = $_POST['password'];
        }else{
            $errors .= "blablabla";
        }

    //I make the query
    $sql = "SELECT user FROM users WHERE user = ?";

    //I prepare the query
    if($stmt = $con->prepare($sql)){

         $stmt->bind_param('s', $user);
         $result = $stmt->execute();

    }

    /* UP TO HERE, if I check that $result is true and echo "User exists" or something like that, IT WORKS, AS THE USER EXISTS */

    /* BUT now I want to check the PASSWORD, given that the user exists */

        if($result){

            //I make the query
            $sql2 = "SELECT user, password FROM users WHERE user = ? AND password = ?";

            //I prepare the query
            if($stmt2 = $con->prepare($sql2)){

                $stmt2->bind_param('ss', $user, $password);
                $result2 = $stmt2->execute();


                if($result2){
                    echo "ENTERED";
                }else{
                    echo "PASSWORD OR USER INCORRECT";
                }
            }

        } 

?>

I'm using the result of those echos in the success function in the AJAX call, here's the code for that (there's an onClick event (onClick="login()") in the button of the form, and validationLogin() has all the valitations for the fields --> all that works fine):

function login(){

if(validationLogin()){
        $.ajax({

                url: "http://localhost/myProject/extras/Login.php", 
                type: "POST",
                data: {"user": user, 
                       "password": password, 
                       },
                dataType: "html",
                cache: false,
                beforeSend: function() {    
                    console.log("Processing...");
                },
                success: 
                      function(data){

                        alert(data);
                        console.log(data);

                    }

    });

}else{
    //alert("Incorrect fields");
}

}

This returns EMPTY, I alert the data just to check what it has... the alert is empty, don't understand why :/

I've tried this idea --> PHP mySQL check if username and password are in the database but in that case it keeps saying that it's incorrect :/

A few notes:

  • I know that the passwords should be encrypted, will probably use md5 later on.
  • By using the echos in the PHP file and the alert(data) / console.log(data) in the JS file, I just want to check if it works, in order to proceed. Perhaps there are other ways, better ways of doing all this, I know, but I like to go little by little
  • I'm really trying to understand what I code, then will improve on it, I really want to understand how and why it functions or not
  • I would like to continue using prepared statements

Thanks everyone in advance! :)

xragdollqueen
  • 113
  • 4
  • 14
  • 1
    **Never** store plain text passwords. You should use [`password_hash()`](http://us3.php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://us3.php.net/manual/en/function.password-verify.php) instead. If you're using a version of PHP prior to 5.5, do **not** use MD5 or SHA1 to hash passwords. Instead you can use [this compatibility pack](https://github.com/ircmaxell/password_compat). – Alex Howansky May 24 '17 at 15:43
  • @AlexHowansky thanks for the heads up, I've already mentioned something about this at the end of my post. – xragdollqueen May 24 '17 at 15:45
  • *"I've tried this idea --> PHP mySQL check if username and password are in the database but in that case it keeps saying that it's incorrect"* - I've an accepted answer in there (dates back to 2014), so whatever differences there are between the OP's question's code/answer, then something other is failing you. – Funk Forty Niner May 24 '17 at 15:46
  • 1
    If you want to check if rows exist, use `num_rows`, and bind the results; and check for errors; you're not doing that. That's why what you posted failed. – Funk Forty Niner May 24 '17 at 15:47
  • 1
    You don't need two queries. Make one query to get the row. If it doesn't return anything or if the password match fails, then return a generic error. Try to avoid exposing the difference between a non-existing user and an incorrect password. – Alex Howansky May 24 '17 at 15:50
  • [See one of my answers](https://stackoverflow.com/a/22253579/1415724) to check if a row exists. Compare it with what you have now and the missing functions. Which would probably qualify as a possible duplicate. Edit: Seeing that answer below, the link I gave here does qualify as a duplicate. – Funk Forty Niner May 24 '17 at 15:51
  • @AlexHowansky thanks, will keep this in mind! – xragdollqueen May 24 '17 at 16:48

1 Answers1

2

You should try this:

$sql = "SELECT user,password FROM users WHERE user = ?";

//I prepare the query
if($stmt = $con->prepare($sql)){

     $stmt->bind_param('s', $user);
     $result = $stmt->execute();
     if ($result) {
         $stmt->bind_result($user_name,$password_db);    
     } else {
         $user_name="";
         $password_db="";
     }
    // Check Password
    if ($password==$password_db){
        /// PASSWORD IS OK
    }
}

Now you have the user in $user_name and the password in $password (if exists) so you don't need the second sql statement. In the PHP function you can use:

    data: {"user": <?php echo $user_name ?>, 
           "password": <?php echo $password_db ?> , 
           },
nacho
  • 5,280
  • 2
  • 25
  • 34
  • this makes no comparison of the password value – Martin May 24 '17 at 15:54
  • @Martin the answer's correct to a certain point; just not fully. – Funk Forty Niner May 24 '17 at 15:55
  • @Fred-ii- yeah I started writing a recoded answer (no need for `isset` if then using `empty`) which would have a similar impact. I so should spend my days on SO instead on SE: Code Review. Fixing other peoples stuff (for free `:-/`) – Martin May 24 '17 at 16:04
  • @Martin Well, I'm not so much for rewrites myself and "answers" from me are rather more scarce than ever ;-) Teach someone how to fish, is what I like to get into people's minds. – Funk Forty Niner May 24 '17 at 16:15
  • @Fred-ii- I'm waiting for someone to let me in on the secret of the location of a StackOverflow for professional developers, who already know about prepared statements, password handling and SQL character collations and other intro. level issues that dominate SO.... – Martin May 24 '17 at 16:37
  • @Martin Isn't that already [here...](https://stackoverflow.com/documentation/php/topics), sort of? ;-) – Funk Forty Niner May 24 '17 at 16:38
  • @Fred-ii- possibly, I shall explore...... `:-)` – Martin May 24 '17 at 16:46
  • 1
    @Martin I pop that link in questions every once in a while; it contains a lot of code put together by a lot of good coders. They're a tutorial all baked up and ready to gobble up ;-) *Cheers* – Funk Forty Niner May 24 '17 at 16:49
  • @Fred-ii- om nom [nom](http://www.omnomnomnom.com/random/) nom [nom](http://www.omnomnomnom.com/random/) om ...... thanks – Martin May 24 '17 at 16:51
  • @Fred-ii- I've just bookmarked that link ;) oh my.. thanks for the answers and the other post. I'll try with num_rows again... There must be some error somewhere else, because to me the queries are ok.. My problem lies in what to do with the results and also what the ajax receives.. I'm reading and trying to put everything together, but sometimes it just doesn't "click" so easily... Anyway, thanks for the help! :) – xragdollqueen May 24 '17 at 16:57
  • 1
    You're welcome @xragdollqueen have a look at the link I duplicated the question with; I can't see that failing. If it does fail, then it would have something to do on your end. Make sure that the data is correct in the database and that there was no whitespace introduced. That I've seen happen quite a few times and just makes someone's day turn sour. Use error checking everywhere; be it via the developer console, php and mysql; you'll get it, I'm sure of it ;-) – Funk Forty Niner May 24 '17 at 17:00