Skip to content
PHP Logo

How can PHP scripts be structured to ensure that authentication through login.php is required before accessing admin.php?

To ensure that authentication through login.php is required before accessing admin.php, you can use sessions to store the user's authentication status. When a user successfully logs in through login.php, set a session variable to indicate that they are authenticated. In admin.php, check for this session variable and redirect the user back to login.php if they are not authenticated.

php
// login.php
session_start();

// Perform authentication check here

// If authentication is successful, set session variable
$_SESSION['authenticated'] = true;

// admin.php
session_start();

// Check if user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    header("Location: login.php");
    exit();
}

// Proceed with admin functionality