如果没有登录,PHP重定向


PHP redirect if not logged in

我一直在努力使以下功能在我的网站上工作,但我有点挣扎。也许你们谁能帮我一下?

我正在开发一个网站,必须是不可访问的(除了登录当然),除非你登录。我试图使一个自动重定向到登录页面,如果用户没有登录。我正在使用HTML, CSS和PHP的时刻。

如果需要我的剩余资源请告诉我,我将暂时在线托管网站

如果您没有使用任何框架,请简单尝试:

if(!isset($_SESSION['login'])){ //if login in session is not set
    header("Location: http://www.example.com/login.php");
}

会话参数和重定向位置取决于您在web项目中使用的架构

<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

或javascript

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

当您确定他们没有登录时,您可以发出重定向头:

header("Location: http://www.example.com/log-in/");

您正在使用的登录脚本已经在检查用户id是否在index.php中登录:

if ($login->isUserLoggedIn() == true) {
    // the user is logged in. you can do whatever you want here.
    // for demonstration purposes, we simply show the "you are logged in" view.
    include("views/logged_in.php");
} else {
    // the user is not logged in. you can do whatever you want here.
    // for demonstration purposes, we simply show the "you are not logged in" view.
    include("views/not_logged_in.php"); // Change this part to your needs.
}

您可以将include("views/not_logged_in.php");更改为您想要的任何页面