如果用户未登录,则执行代码

时间:2017-08-10 09:20:35

标签: php session login

我在index.php(登录页面)上面有这个代码。我正在尝试在访问登录页面时将登录用户重定向到各自的页面上。如果用户没有登录,我想执行登录页面。这是我的代码。

<?php   
session_start();
if($_SESSION['access_level'] == 0){
    header("Location: admin/home.php");
}
if($_SESSION['access_level'] == 1){
    header("Location: user/home.php?err=logged-in");
}
if($_SESSION['access_level'] == 2){
    header("Location: businesshead/home.php");
}
if($_SESSION['access_level'] == 3){
    header("Location: scma/home.php");
}
if($_SESSION['access_level'] == 4){
    header("Location: scm/home.php");
}
if($_SESSION['access_level'] == 5){
    header("Location: finance/home.php");
}
if($_SESSION['access_level'] == 6){
    header("Location: gm/home.php");
}
if(!isset($_SESSION['access_level'])){ //if login in session is not set
    header("Location: index.php");
}
?>

非常感谢你! :)

编辑: 我的问题是,如果我将此代码放在我的index.php文件之上,会发生无限循环并导致它无法运行。

如果用户未登录,请执行登录页面。如果用户已登录(并尝试访问登录页面),请将其重定向到各自的页面。

2 个答案:

答案 0 :(得分:0)

你忘记了标题

之后的exit()
<?php    
   header("Location: admin/home.php");   
  exit();      
?>

<?php    
       header("Location: admin/home.php");   
      exit;      
    ?>

此链接可以帮助您: http://php.net/manual/en/function.header.php

答案 1 :(得分:0)

您的代码并不美观,我们假设您的登录页面为login.php,并且任何访问都有默认位置。

登录后:

$access_location[0] = 'admin/home.php';
$access_location[1] = 'user/home.php?err=logged-in';
$access_location[2] = 'businesshead/home.php';
$access_location[3] = 'scma/home.php';
$access_location[4] = 'scm/home.php';
$access_location[5] = 'finance/home.php';
$access_location[6] = 'gm/home.php';

session_start();

if (!isset($_SESSION['access_level'])) { //if login in session is not set
    header("location: login.php");
    exit();
}else{
  header("location:".$access_location[(int) $_SESSION['access_level']]);
  exit();
}

并且在任何重定向之后,您必须从代码中exit()

相关问题