如何将未登录的用户重定向到索引页?


How can I redirect a not logged in person to the index page?

我希望一个没有登录的人被重定向到索引页。

在我的onlymembers.php中,我添加了以下代码:

if(!$user->is_logged_in()){ 
echo "you are not logged in";
header("Location: index.php");
} 

打印出"you are not logged in",这表明登录检查正在工作。但我不会被重定向到索引页。你知道为什么吗?


更新:

我现在使用这段代码,它正在工作:

if(!$user->is_logged_in()){ 
header("Location: index.php"); 
} 

我实际上不知道为什么。我只是删除了一些空白:-/


再次更新:我现在知道问题了:我刚刚在我的页面....的开头删除了<?php前面的空白

在使用HTTP重定向之前,您不能发送页面的内容(您的代码应该有一个PHP错误,如"headers already sent")。你要么使用javascript重定向,要么删除"echo":

if(!$user->is_logged_in()){ 
    header("Location: index.php");
}

在向用户发送可视输出后,不能发送HTTP头。您可以使用带有刷新条件的标头,该条件允许您向用户发送输出。

if(!$user->is_logged_in()){ 
header("Refresh: 5; url=./index.php");
//after 5 seconds the user gets redirected. To change the period of time just change the number after "Refresh"
echo "you are not logged in";
exit();
} 

注:总是建议你使用exit()函数(就像我做的那样)当你想要强制重定向用户以确保安全。

你也可以在重定向链接上放一个变量,然后在index.php上解析它来显示消息,像这样…

if(!$user->is_logged_in()){ 
$msg = "you are not logged in";
    header("Location: index.php?reply=$msg");
exit();
    } 

附加的index.php代码

if(!empty($_GET['reply'])) {
$reply = $_GET['reply'];
}

然后是$reply变量,它包含可以在索引中显示的消息。

如果位置重定向不起作用,那么你可以使用javascript。

<script>
 window.location = "http://www.redirecturl.com/"
</script>
  1. 将if语句移到头文件上面include.
  2. ob_start()在脚本的顶部缓冲输出。

    if(!$user->is_logged_in()){    
        echo "you are not logged in";    
        ob_start();    
        header("Location: index.php");    
    }
    

<script>                
    var url = "http://yoururl.com";    
    window.location.href = url;
</script>

Header函数应该在html标签之前使用。

的例子:

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>