0

I'm doing a project for the school and I'm having some troubles with this login, I know how to do it in a different way, but I would like to learn how to do it this way.

I don't really know why its not working (some parts probably don't have any logic and is why its not working), it always says the error message "Invalid credentials" from the alert.

Here is my code:

<html>
<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#loginform').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: 'loginFinal.php',
                    data: $(this).serialize(),
                    success: function(data) {
                        if (data === 'CORRECTO') {
                            window.location = 'index.php';
                        }
                        else {
                            alert('Invalid credentials');
                        }
                    }
                });
            });
        });
    </script>

</head>
<body>
    <form id="loginform" method="post">
        Username: <input type="text" name="username" id="username" value="">

        Password: <input type="password" name="password" id="password" value="">

        <input type="submit" name="loginsub" id="loginsub" value="Login">
    </form>
</body>
</html>

And here is the PHP:

function Login() {
        $success = false;           
        try {
            $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
            $sql = "SELECT * FROM users WHERE username = ".$_POST['username']." AND password = ".$_POST['password']." LIMIT 1";

            $stmt = $con->prepare( $sql );

            $stmt->execute();

            $valid = $stmt->fetchColumn();

            if( $valid ) {
                $success = true;

                session_start();
                session_regenerate_id();
                $_SESSION['user'] = $_POST['username'];
                session_write_close();
                echo ('CORRECTO');

                exit();
            }

            $con = null;
            return $success;
        }
        catch (PDOException $e) {
            echo $e->getMessage();
            return $success;
        }
    }
11
  • 3
    Your script is wide open to SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements in either the MYSQLI_ or PDO API's Commented Apr 20, 2018 at 22:25
  • 1
    Where do you call the function Login() Commented Apr 20, 2018 at 22:26
  • I don't, i don't know how to do it or where Commented Apr 20, 2018 at 22:27
  • Is that the whole file loginFinal.php? Commented Apr 20, 2018 at 22:28
  • 1
    Please don't store plaintext passwords :( Commented Apr 20, 2018 at 22:32

3 Answers 3

1

Made the below code use prepared statement. Your ajax looks fine. Just the below function that's not.

Updated Code:

   function Login() {
            $success = false;           
            try {
                $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
                $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

                $stmt = $con->prepare( $sql );

                $stmt->execute(array(':username'=>$_POST['username'], ':password'=>$_POST['password']));

                $valid = $stmt->fetchColumn();

                if( $valid ) {
                    $success = true;
                    session_start();
                    session_regenerate_id();
                    $_SESSION['user'] = $_POST['username'];
                    session_write_close();
                    echo ('CORRECTO');
                    exit();
                }

                $con = null;
                return $success;
            }
            catch (PDOException $e) {
                echo $e->getMessage();
                return $success;
            }
        }

 Login();

^ And the function has to be executed for the response to be sent.

Sign up to request clarification or add additional context in comments.

5 Comments

Still always getting invalid credentials, i think the problem is that i never enter to the funtion Login, cuz i put an alert in the firt line of the function and it never shows up, should i call it somewhere? because if i delete the "function Login() {" line and the closing bracked im getting a "http 500 error, server internal error"
Yes. You need to call Login() function somewhere for your code to work as required. Make sure only the Login() function outputs something.
Worked! Thanks you!
It also work deleting de "function Login() {" line and the closing bracked, don't know why wasn't working yesterday because i already tried this. Thanks for the help!
0

I has code of login with php and ajax, i hope understand my example. in you php scrip, you have example: echo 'correcto', when is echo json_encode(array('error' => true , 'mensaje' => "usuario o password incorrectos"));

for you:

echo json_encode(array(message => 'CORRECTO'));

and you script js

success: function(data) {
  if (data.message == 'CORRECTO') {
    window.location = 'index.php';
  }else{
   // other code
  }
}

Create at script only php, without class name.. only php. and instance you class when you have exist method login.. and in you method login pass parameters

$user = $_POST['username'];
$pass = $_POST['password'];

    <?php

    include_once "conexion.php";

     $user = $_POST['username'];
     $pass = $_POST['password'];
     if($_POST){
       $class = new Class();
        if( $class->login($user,$pass))
          echo json_encode(array(message => 'CORRECTO'));
        else
         echo json_encode(array(message => 'ERROR'));
     }

    ?>

// en your class when function
    function Login($user,$pass) {
            $success = false;           
            try {
                $con = new PDO( 'mysql:host=localhost;dbname=MY_DB_NAME', 'MY_USRNAME', 'MY_PSW' );
                $sql = "SELECT * FROM users WHERE username = ".$user." AND password = ".$pass." LIMIT 1";

                $stmt = $con->prepare( $sql );

                $stmt->execute();

                $valid = $stmt->fetchColumn();

                if( $valid ) {
                    $success = true;
                    session_start();
                    session_regenerate_id();
                    $_SESSION['user'] = $_POST['username'];
                    session_write_close();
                    $success = true;
                    exit();
                }
                $con = null;
                return $success;
            }
            catch (PDOException $e) {
                echo $e->getMessage();
                return false;
            }
        }

I hope help you

8 Comments

Thanks for the answer, but still getting always invalid credentials with ur changes.
I have this now:
type: "POST", url: 'loginFinal.php', dataType: 'json', data: $(this).serialize(), success: function(data) { if (data.message == 'CORRECTO') { window.location = 'index.php'; }else{ alert("not correct"); } }
can't press the "Login" button now
how call you method Login() ?
|
0

Could you do var_dump ($_REQUEST) to see what do you send to the server?

(I think when you click the submit button the page get refreshed?)

Update:

1- change the submit to a button:

<input type="button" name="loginsub" id="loginsub" value="Login">

2- Use jQuery to trigger the call:

$('#loginsub').on('click',function(){
    var data={};
    data['username']=$('#username').val();
    data['password']=$('#password').val();
    //put the ajax call here, and replace $(this)serialize() with data
});

6 Comments

where and how??
on the top of your php file, justput this code to see what ajax sends out to the php file: var_dump($_REQUEST); exit;
in the console (use the inspect element > console), you'll see the Call
ye i always have the console open, but im not getting response. Copy pasted ur code on the top of the php file but inside the "<?php" tag
do you see the ajax call in the console or not?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.