Search code examples
phpsessionauthenticationuid

Restrict Page to Specific Session ID


I wrote a simple login system and that is working. I've set up a few pages that are only viewable when logged in. I want to restrict a page to specific session IDs. How would I go about doing that? This is what I'm using to restrict pages right now:

<?php
session_start();
 if (!isset($_SESSION['u_id'])) {
 header("Location: ../index.php?index=mustlogin");
 exit();
}
?>

How would I restrict this from any u_id to a specific u_id?


Solution

  • You can create an array of specific ids and then use in_array to validate user.

    Example

    <?php
    session_start();
    $sessionIds = array('1','2'); //for example i have inserted 1 and 2 as ids
     if (!isset($_SESSION['u_id']) || in_array($_SESSION['u_id'], $sessionIds))  {
     header("Location: ../index.php?index=mustlogin");
     exit();
    }
    

    Explanation

    Here i created an array $sessionIds of specific ids that will not allow to access page. then cheking with in_array that current session user id exist in $sessionIds array then redirect to user.