jeudi 27 décembre 2018

How to prevent / escape access restriction as a logged in / registered user?

If a page has a restriction for not registered users trying to access your page such as

if (!isset($_SESSION['username'])){
    header('location: login.php');
    exit;
}

it means that each time your login session is not set you should be redirected to the login page, but if you have the right combination of the required information the code should set a session for you and let you pass through this restriction as a registered user to the website you are trying to access.

Well, this is not happening in my case, after i sat a restriction for anyone trying to access the website manually (which is the code above) i got restricted to access the website even as a registered user even when i try to log in with existing username and password...

So basically it keeps redirecting me to the login.php no matter what i do and I am looking for a way to access my landing page after a successful login

Here is my login code:

<?php
session_start();
$mysqli = new mysqli('localhost','root','password','accounts');
$_SESSION['message'] = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $user = $mysqli->real_escape_string($_POST['username']);
        $pass = $mysqli->real_escape_string($_POST['password']);
        $sql = "SELECT * FROM users WHERE username = '$user' ";
        $result = mysqli_query($mysqli, $sql);
        $id = mysqli_query($mysqli,"SELECT name FROM users WHERE username = '$user'");

        while ($row = $id->fetch_array()) {
            $_SESSION['name'] = $row['name'];
        }

        if (mysqli_num_rows($result)>0){
            while($row = mysqli_fetch_array($result)){
                if(password_verify($pass, $row['pass'])){ 
                    $_SESSION['username'] = $user; 
                    $_SESSION['message'] = "Login Success!";
                    header("location: index.php");
                }
                else{
                    header("location: login.php");
                    $_SESSION['message'] = "Incorrect Password!";
                }
            }
        }
        else{
            header("location: login.php");
            $_SESSION['message'] = "Username does not exist!";
        }

}
?>

At least i am getting a "Login Success!" message at my Login page...

Aucun commentaire:

Enregistrer un commentaire