How to authenticate user correctly?

Asked

Viewed 35 times

-1

Well I’m doing a login system in php and mysql, it works well, but works well even too. When I try to log in with the correct login and password the authentication.php file authenticates them perfectly, for example: login=test and password=123. But when I try to change login, for example: login=Test and password=123; the file authenticates normally. As I fix, this?

The code of authentication.php:

<?php
    session_start();
    include("connection.php");

    $btnLogin = filter_input(INPUT_POST, 'btnLogin', FILTER_SANITIZE_STRING);

    if($btnLogin){
        $user = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
        $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
        //echo "$user - $password";
        if ((!empty($user)) AND (!empty($password))){
            $result_user = "SELECT id, user, password FROM accounts WHERE user='$user' LIMIT 1";
            $resulted_user = mysqli_query($conn, $result_user);
            if ($resulted_user){
                $row_user = mysqli_fetch_assoc($resulted_user);
                if(password_verify($password, $row_user['password'])){
                    $_SESSION['id'] = $row_user['id'];
                    $_SESSION['user'] = $row_user['user'];
                    }
                    header("Location: /repo/main.php");
                }else{
                    $_SESSION['msg'] = "Login or password incorrect";
          header("Location: /repo/index.php");
                }
            }
        }else{
            $_SESSION['msg'] = "Login or password incorrect";
      header("Location: /repo/index.php");
        }
    }else{
        $_SESSION['msg'] = "Page Not Found";
    header("Location: /repo/index.php");
    }
?>

1 answer

0

The problem is in the query made to SQL, because, by default, this search will be case insensitive, as stated in the Mysql documentation.

To solve this problem, as suggested in the documentation itself, one should add a collate to the query. Which one to add depends on your case and may be the same as what is already used, but case sensitive.

Ex:

SELECT id, user, password FROM accounts WHERE user COLLATE latin1_general_cs = '$user' LIMIT 1

Honestly, I wouldn’t recommend anyone developing authentication/authorization code unless they want to learn in depth about it. If the goal is to have this resource and not learning (and for this it would be important to delve deeply into the subject), I would recommend looking for a ready-made solution or check how it is done in some large and open source projects. For this, you can look to see a framework or Wordpress, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.