khizar067
khizar067

Reputation: 37

How to secure my PHP webpage from unauthorized Users

I am new in PHP and facing a problem with security. I use this to redirect unauthorized users if they not logged in.

<?php
session_start();

if(!isset($_SESSION['user_id'])) {
    header('Location: login.php');
}
?>

It is on every top of my page but when I log in and click my protected page it will redirect to login page instead of original/protected page open and my session variable is set on my login page how to include this session variable in my protected page from login page.

Upvotes: 0

Views: 233

Answers (2)

Seabody
Seabody

Reputation: 1217

Try this:

if(!isset($_SESSION['user_id']))
{
    // The user id variable is not set. Therefore, the user is most likely a guest.
    $_SESSION['user_id'] == 0;
}
if($_SESSION['user_id'] == 0)
{
    // The user does not have a user id set. We assume, therefore, that they are a guest.
    header("Location: login.php");
}

Also, in your login script, ensure that you are setting $_SESSION['user_id'] to anything other than 0.

Upvotes: 0

samayo
samayo

Reputation: 16495

If when, you log in, it sends you to login page, then $_SESSION['user_id'] may not be set, or you aren't including session in your file, to check it, do:

var_dump($_SESSION['user_id'])

on the page, and temporally leave out the header if the var_dump returns NULL, it means, $_SESSION['user_id'] is not set

Upvotes: 1

Related Questions