Search code examples
phpbuttonhideadmindisplay

PHP check if user is an admin/user and display buttons


I'm not a pro in PHP so need a little help.

I have a log in function on my website which checks if user is an admin or a normal user which works perfectly fine.

I'm adding a new functionality where the system should check if user is logged in and display different buttons.

  • If user is not logged in then display sign in/sign up buttons.
  • If user is logged in as a user then display user.php button and
    logout.php
  • If user is an admin then display admin.php and logout.php

However, it only works for a user. What am I missing? UserTypeID is set up 1 for a user and 2 for an admin in the database.

session_start();
<?php
if(isset($_SESSION['UserTypeID']) == 1) //check if user is a user and display buttons
{
?>
    <li><a href="user.php">My Account</a></li>
    <li><a href="logout.php">Logout</a></li>

<?php } elseif(isset($_SESSION['UserTypeID']) == 2) //check if user is an admin and display buttons
{
?>
    <li><a href="admin.php">My Account</a></li>
    <li><a href="logout.php">Logout</a></li>

<?php  }else{ // if user is not logged in then display these buttons?> 
    <li><a href="signin.php">Sign In</a></li>
    <li><a href="signup.php">Sign Up</a></li>
<?php } ?>



Solution

  • isset($_SESSION['UserTypeID']) returns true or false

    session_start();
    <?php if(isset($_SESSION['UserTypeID']) && $_SESSION['UserTypeID']== 1) //check if user is a user and display buttons
        {
        ?>
        <li><a href="user.php">My Account</a></li>
        <li><a href="logout.php">Logout</a></li>
    
        <?php } elseif(isset($_SESSION['UserTypeID']) && $_SESSION['UserTypeID'] == 2) //check if user is an admin and display buttons
        {
        ?>
        <li><a href="admin.php">My Account</a></li>
        <li><a href="logout.php">Logout</a></li>
    
    
    <?php  }else{ // if user is not logged in then display these buttons?> 
    <li><a href="signin.php">Sign In</a></li>
    <li><a href="signup.php">Sign Up</a></li>
    <?php } ?>