如果未登录,PHP 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16735747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:37:54  来源:igfitidea点击:

PHP redirect if not logged in

phpredirect

提问by J.I.N Kleiss

I have been trying to make this following functionality work on my website, however I'm kinda struggling with it. Perhaps one of you can help me out?

我一直试图在我的网站上使用以下功能,但是我有点挣扎。也许你们中的一位可以帮助我?

I am developing a website which must be inaccessible (except the login of course) unless you are logged in. I was trying to make an automatic redirect to the login page if the user isn't logged in. I'm using HTML, CSS, and PHP at the moment.

我正在开发一个必须无法访问的网站(当然除了登录),除非您登录。如果用户未登录,我试图自动重定向到登录页面。我正在使用 HTML、CSS ,和 PHP 此刻。

If my remaining source is needed please tell me, I'll temporarily host the site online.

如果需要我的剩余资源,请告诉我,我将临时在线托管该站点。

回答by Dropout

If you're not using any frameworks, try simply:

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

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

The session parameter and the redirect location depends on the architecture that you're using on your web project.

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

回答by Igor S.

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

or in javascript

或在 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";

回答by Fenton

When you determine that they are not logged in you can issue a redirection header:

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

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

This is described in detail in the PHP Manual: Header.

这在PHP 手册: Header中有详细描述。

回答by MISJHA

The login script you are using is already checking if the user id logged in in the index.php:

您正在使用的登录脚本已经在检查用户 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.
}

You can change this include("views/not_logged_in.php");to whatever page you want.

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