Home » Php » php – Two users on a session filter

php – Two users on a session filter

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created a website that allows users to log on and check various assets within the organisation. I want to be able to filter certain pages down to specific users. I have managed to get a page so that only one particular user can access it, but what I want to do is add multiple users to this. The code that I have and works is;

<?php
// Initialize the session
session_start();

// Check which user is logged in, if not allowed access redirect him to error page
if(!isset($_SESSION["username"]) || $_SESSION["username"] !== 'User1')
{
header("location: error.html");
exit;
}
?>

How do I add it so that both User1 and User2 have access to this page but noone else.

Thanks in advance

How to&Answers:

You can use a array.

<?php
// Initialize the session
session_start();

$allowedUsers = [
    'User1',
    'User2'
];

// Check which user is logged in, if not allowed access redirect him to error page
if(!isset($_SESSION["username"]) || !in_array($_SESSION["username"], $allowedUsers))
{
    header("location: error.html");
    exit;
}
?>