Skip to content
Advertisement

Admin only access to page, if statment doesn’t work

I’m trying to give access to admin tools only to the admin.

What I tried to do: the session variable id, which is unique for every user. first I checked if there is even a session, if there isn’t I send the user to the index, than I check for the unique if of the admin “20” if the user’s id is different than 20 I send him the the index.

my problem: my if statment doesn’t work, I get sent back to index even when i’m logged-in as the admin.

My code:

<?php 
if(isset($_SESSION['userId'])){
    header('Location:index.php?b');
}
if($_SESSION['userId'] != 20){
      header('Location:index.php?a');
}

?>

?a and ?b are for debugging, I get sent to index.php?a when I try to access the my page.

when I echo $_SESSION['userId'] I get 20, so maybe something is wrong with the type?(although I checked and it says that != shouldn’t be effected by different types)

EDIT: sorry, I didn’t describe what I wanted correctly, if the id of the user is 20 I want him to stay in the page, if it isn’t I want to redirect him to index.

thanks!

Advertisement

Answer

Because you perform one test when that test passes or fails the comparison is over. You should probably perform a comparison like this because you only want to redirect when the ID is not 20:

<?php
session_start();
if(isset($_SESSION['userId']) && $_SESSION['userId'] != 20) {
    header("Location: index.php");
    exit();
}
?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement