PHP 检查用户是否是 admin/user 并显示按钮

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

我不是 PHP 的专家,所以需要一点帮助。

我的网站上有一个登录功能,可以检查用户是管理员还是普通用户,这个功能非常好。

我正在添加一项新功能,系统应检查用户是否已登录并显示不同的按钮。

但是,它只对一个用户有效。我错过了什么? UserTypeID 在数据库中为用户设置 1,为管理员设置 2。

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 } ?>


做类似 this.This 的事情会奏效。

<?php 
session_start();
if(!empty($_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 } else if(!empty($_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 } ?>

isset($_SESSION['UserTypeID']) returns truefalse

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 } ?>

session_start()函数需要写在php里面,编码如下:

  <?php 
    session_start();
    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 } ?>