Skip to main content

Protecting Pages and Preventing Unauthorised Access

InA protected page checks authentication on the previousserver tutorial,before yousending usedrestricted PHPcontent. sessionsHiding toa remembermenu wholink wasis loggednot in.protection Inbecause a user can enter the URL directly.

Require a logged-in user

Place this tutorial, you will prevent users from accessing protected pages unless they have successfully logged in.


The Problem

Currently, anyone can access:

http://localhost/members.php

even if they have not logged in.

To secure the page, we need to check whether a valid session exists before displaying any content.


Open the Members Page

Open:

members.php

Your page should currently begin with:

<?php

session_start();

?>

Check if the User is Logged In

Add the following code immediately after session_start():

if (!isset($_SESSION["user_id"])) {

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

}

Your page should now begin with:HTML:

<?php
session_start();

if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();exit;
}

?>

This checks whether the session contains a user_id.

If it does not, the user is redirected to the login page.


Test the Protection

Open a private or incognito browser window.

Attempt to visit:

http://localhost/members.php

Instead of seeing the members page, you should be redirected to:

http://localhost/login.php

Test After Logging In

Log in using a valid account.

Example:

Username: admin
Password: password123

After logging in, you should be redirected to:

http://localhost/members.php

The pageexit should display your username.

Create a Second Protected Page

Create a new file called:

settings.php

Addprevents the followingrest code:

<?php

session_start();

if (!isset($_SESSION["user_id"])) {

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

}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Settings</title>
</head>
<body>

<h1>Settings Page</h1>

<p>Only logged-in users can view this page.</p>

</body>
</html>

Save the file.


Test the Settings Page

Visit:

http://localhost/settings.php

If you are logged in,of the page shouldfrom load.

running

If you are not logged in, you should be redirected toafter the login page.redirect.

Reusing the Protection Code

Any page that should require a login can use the same code:

<?php

session_start();

if (!isset($_SESSION["user_id"])) {

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

}

?>

Examples:

members.php
settings.php
profile.php
dashboard.php

Complete Protectedprotected Members Pagepage

<?php
session_start();

if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();exit;
}

$username = $_SESSION["username"] ?? "user";
?>
<!DOCTYPEdoctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Members AreaDashboard</title>
</head>
<body>
  <h1>MembersUser Areadashboard</h1>
  <p>Welcome, <?php= echo htmlspecialchars($_SESSION["username"];username) ?>
</p>

<p>User ID:
<?php echo $_SESSION["user_id"]; ?>
.</p>
</body>
</html>

Use a reusable guard

YouCreate nowincludes/require-login.php:

have
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit;
}

Then begin protected pages thatwith:

can
require only__DIR__ be. accessed"/includes/require-login.php";

Test direct access

Use a private browser window or log out, then enter the protected URL directly. Also test after closing the browser and after destroying the session.

Check

     Authentication is checked before output.  Redirect is followed by authenticatedexit. users.

    NextEvery tutorial:protected Creatingprocessing aroute Logoutuses Page.

    the guard.  Direct URL access is tested.  Displayed session values are escaped.