skip to Main Content

Am trying to direct a user to admin dashboard after login if user name and password exist in the database. if not then direct user back to the login page. But is not working when the user enters his details instead of going to the admin dashboard page it is directed back to the login page even though users details are in the database. The problem is with the admin-dashboard.php file if I comment out "header(‘location:index.php’);" it works perfectly but user can access the admin-dashboard without logging in form the url search bar and i don’t want that way

This is my index.php

    <?php
session_start();
if(isset($_SESSION['username'])){
   header('location:admin-dashboard.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | Admin</title>
    <!-- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.22/datatables.min.css"/> -->
    <link rel="stylesheet" href="assets/css/style.css" type="css/text">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"/>
<style type="text/css">
html,body{
    height:100%;

}
</style>
</head>
<body class="bg-dark">
    <div class="container h-100">
        <div class="row h-100 align-items-center justify-content-center">
            <div class="col-lg-5">
                <div class="card border-danger shadow-lg">
                    <div class="card-header bg-danger">
                        <h3 class="m-0 text-white"><i class="fas fa-user-cog"></i>&nbsp;Admin Panel Login</h3>
                    </div>
                    <div class="card-body">
                        <form action="action" method="post" class="px-3 " id="admin-login-form"> 
                            <div id="adminLoginAlert"></div>
                            <div class="form-group">
                                <input type="text" name="username" class="form-control 
                                form-control-lg rounded-2" placeholder="Username" required autofocus>
                            </div>
                            <div class="form-group">
                                <input type="password" name="password" class="form-control 
                                form-control-lg rounded-2" placeholder="Password" autocomplete= required>
                            </div>
                            <div class="form-group">
                                <input type="submit" name="admin-login" class="btn btn-danger
                                btn-block btn-lg rounded-2" value="Login" id="adminLoginBtn">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/js/all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
<script type="text/javascript">
    $(document).ready(function(){
// sending ajax request to server
    $("#adminLoginBtn").click(function(e){
    if($("#admin-login-form")[0].checkValidity()){
            e.preventDefault();
                $(this).val('Please Wait...');
                $.ajax({
                    url:'assets/php/admin-action.php',
                    method:'post',
                    data:$("#admin-login-form").serialize()+'&action=adminLogin',
                    success:function(response){
                        if($.trim(response) == 'register'){
                            window.location = 'admin-dashboard.php';
                        }
                        
                        if(response === 'admin_login'){
                            window.location = 'admin-dashboard.php';
                        }
                        else{
                            $("#adminLoginAlert").html(response);
                        }
                        $("#adminLoginBtn").val('Login');
                    }
                });
            }
        });
    });
</script>
</body>
</html>

My admin-dashboard.php

 <?php
session_start();
if(!isset($_SESSION['username'])){
   header('location:index.php'); 
   exit();
  
}
?>
<a href="assets/php/logout.php">Logout</a>

My config.php

  <?php
class Database {
    
    private $dsn = "mysql:host=localhost;dbname=database_user_system";
    private $dbuser = "root";
    private $dbpass = "";

    public $conn;

    public function __construct(){
        try{
            $this->conn = new PDO($this->dsn,$this->dbuser,$this->dbpass);
               
              

        }catch (PDOExeception $e) {
            echo 'Error :'.$e->getMessage();

        }
        return $this->conn;
    }
    // Checking Input 
    public function test_input($data){
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    // Error success message alert
    public function showMessage($type,$message){
        return '<div class="alert alert-'.$type.' alert-dismissible "> 
                    <button type="button" class="close" 
                    data-dismiss="alert">&times;</button>
                    <strong class="text-center"> '.$message.' </strong>
                    
                     </div>';
    }

    
}




?>

My logout.php

<?php
session_start();
unset($_SESSION['username']);
header('location:../../index.php'); 


?>

My admin-action.php

    <?php
require_once 'admin-db.php';

$admin = new Admin();

    // Handle admin login ajax Request

if(isset($_POST['action']) && $_POST['action'] == 'adminLogin'){
    $username = $admin->test_input($_POST['username']);
    $password =$admin->test_input($_POST['password']);


    $hpassword = sha1($password);
    $loggedInAdmin = $admin->admin_login($username,$hpassword);

    if($loggedInAdmin !=null){
        echo 'admin_login';
        $_SESSION['username']= $username;
    }
    else {
      echo  $admin->showMessage('danger', 'Username or Password is Incorrect!');}
    }

    ?>

My admin-db.php

<?php
require_once 'config.php';

//creating new object of admin class in admin-action.php
class Admin extends Database {
    // Admin login

    public function admin_login($username, $password)
    {
       $sql = "SELECT username,password FROM admin WHERE username = :username AND 
       password = :password";

       $stmt = $this->conn->prepare($sql);
       $stmt->execute(['username'=>$username,'password'=>$password]);
       $row = $stmt->fetch(PDO::FETCH_ASSOC);

       return $row; 
    }
}
?>

2

Answers


  1. I think you need your location header to be an absolute path with HTTP 1.1 as specified in the PHP documentation. header('Location: http://localhost/admin-dashboard.php'); or call within exit, exit(header('Location: http://localhost/admin-dashboard.php'));

    See here for more detail

    Login or Signup to reply.
  2. First of all fetch data from the database
    if the result is greater than 0
    it redirects with the below code

    <?php
    require_once 'config.php';
    
    //creating new object of admin class in admin-action.php
    class Admin extends Database {
        // Admin login
    
        public function admin_login($username, $password)
        {
           $sql = "SELECT username,password FROM admin WHERE username = :username AND 
           password = :password";
    
           $stmt = $this->conn->prepare($sql);
           $stmt->execute(['username'=>$username,'password'=>$password]);
           $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if($row > 0){
    header('location:index.php);
    }else{
    header('location:error.php);
    }
    
      }
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search