1

I'm setting a web application for an E-commerce project which has an administrator panel. How do I force and auto redirect to login.php instead of index.php?

For instance, if I did follow this path http://localhost/project/admin (this will load index.php).

However, the login process runs successfully and session opened when I try to open login.php manually via http://localhost/project/admin/login.php

Folder Structure:

  • Both index.php and login.php are in admin folder
  • connection.php, admin-header, admin-footer are in include folder Path http://localhost/project/admin

using XAMPP Panel v3.2 on windows 10

I've tried the below:

login.php

<?php
    session_start();
    include '../include/connection.php';

    if (isset($_POST['submit'])) {
        $email = $_POST['email'];
        $password = $_POST['password'];
        $query = "select * from admin where admin_email = '$email' AND admin_password = '$password'";
        $result = mysqli_query($conn,$query);
        $adminSet = mysqli_fetch_assoc($result);
        if ($adminSet['admin_id']) {
            $_SESSION['admin_id'] = $adminSet['admin_id'];
            header("location:index.php");
        }
        else {
            $error = "You are not authenticated.";
        }
    }
?>

admin-header.php // which included on index.php

<?php
    session_start();
    if (!isset($_SESSION['admin_id'])) {
        header("location:login.php");
    }
?>

index.php

<?php include '../include/admin-header.php'?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Moh Shalan
  • 19
  • 2
  • 1
    note: [should-i-call-exit](https://stackoverflow.com/questions/3553698/php-should-i-call-exit-after-calling-location-header) – jibsteroos Aug 22 '19 at 21:04

1 Answers1

5

Option1 (DirectoryIndex)

In your admin directory, create an .htaccess file with this content:

DirectoryIndex login.php

Option2 (RewriteRule)

In your admin directory, create an .htaccess file with this content:

RewriteEngine On
RewriteRule index.php login.php [L]

I tested option 2 and it works fine if you requested /admin or /admin/ or /admin/index.php , you will get redirected to login.php in the 3 cases

Option 3 (HTTP redirect)

Make your index.php like this:

<?php
    header("Location: login.php");
    exit;

I don't prefer option 3 to save the extra HTTP request.

Make sure your Apache is allowing .htaccess files

Check this question also.

Accountant م
  • 6,975
  • 3
  • 41
  • 61