Skip to main content

Protecting Pages and Preventing Unauthorised Access

In the previous tutorial, you used PHP sessions to remember who was logged in. In 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:

<?php

session_start();

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

    header("Location: login.php");
    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 page should display your username.

Create a Second Protected Page

Create a new file called:

settings.php

Add the following 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, the page should load.

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

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 Protected Members Page

<?php

session_start();

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

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

}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Members Area</title>
</head>
<body>

<h1>Members Area</h1>

<p>Welcome,
<?php echo $_SESSION["username"]; ?>
</p>

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

</body>
</html>

You now have pages that can only be accessed by authenticated users.

Next tutorial: Creating a Logout Page.