简体   繁体   English

如果用户登录,则自动重定向

[英]Auto redirect if user is logged in

I've two pages: index.php and register.php . 我有两个页面: index.phpregister.php If the user is guest , he can click on register.php -->go to that page-->register a form and login. 如果用户是guest ,则可以单击register.php >转到该页面->注册表单并登录。 Upon logging in, he is redirected to index.php. 登录后,他将重定向到index.php。 Now if he/she tries to access signup.php -->they are automatically redirected to index.php . 现在,如果他/她尝试访问signup.php ->它们将自动重定向到index.php I'm using: 我正在使用:

<?php 
   if(!isset($_SESSION['id']))
   {
      //show the form
      ....
   }
   else
   {
      header("Location: index.php");
      exit;
   }
   ?>

How ever, I'm getting a Cannot modify header information error. 但是,出现Cannot modify header information错误。 How else can I make the code to redirect when index.php and register.php are two separate pages. index.phpregister.php是两个单独的页面时,我还能如何使代码重定向。

What I do is create a seperate file named check_logged.php which I include at the top of pages you wish to block. 我要做的是创建一个名为check_logged.php的单独文件,该文件包含在您希望阻止的页面的顶部。 What it does is check whether Add this to the top of your page 它的作用是检查是否将此添加到页面顶部

session_start();
include('php/check_logged.php');

Check_logged.php contains this: Check_logged.php包含以下内容:

if (!empty($_SESSION['id'])) {
    header('Location: index.php');
    exit;
}

Personally I needed a second check because my forms output a confirmation message after you successfully restore your password with this: 就个人而言,我需要进行第二次检查,因为在您成功恢复密码后,我的表单会输出一条确认消息:

if(!isset($_SESSION['good_message'])){ //check if a confirmation message is set, if no continue to check if the user is logged in.
    if (!empty($_SESSION['id'])) {
        header('Location: index.php');
        exit;
    }
}

This way if you return to the login page and want to display a confirmation message it doesn't instantly redirect you. 这样,如果您返回登录页面并要显示确认消息,它不会立即重定向您。 I tend to show my messages like this: 我倾向于显示这样的消息:

<span class="error"> <?php 
    if( IsSet( $_SESSION[ "message_sent" ] ) )  {
            echo "<p align='center' style='color: #8BA870;';> " . $_SESSION[ "message_sent" ] . "</p>";
            unset( $_SESSION[ "message_sent" ] );
}?></span>

It is shown once after which it unsets itself. 它会显示一次,然后自动取消设置。 So if you refresh the page the value is nog longer 'set' and you will be redirected to home. 因此,如果刷新页面,则该值不再“设置”,您将被重定向到主页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM