PHP:如何检查用户是否已经登录,否则重定向到登录页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31031344/
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 22:12:28  来源:igfitidea点击:

PHP: How to check if user is already logged in and otherwise redirect to login page

phpsessionredirectloginsession-variables

提问by TaneMahuta

I am new to PHP and am struggling with the following:

我是 PHP 新手,正在努力解决以下问题:

I have a page where I want to check if someone is a registered user before letting them see the content of the site. So my thought was that in my header file (which is referenced on all single pages via require_once("includes/header.php");) I can check on that and redirect them to a login page (login.php) if they have not logged yet.

我有一个页面,我想在让他们查看网站内容之前检查某人是否是注册用户。所以我的想法是,在我的头文件(在所有单个页面上通过 引用require_once("includes/header.php");)中,我可以检查它并将它们重定向到登录页面(login.php),如果他们还没有登录。

So here is everything that I have in my header:

所以这是我标题中的所有内容:

<!DOCTYPE html>
<html>
    <head>
        <?php 
            define("someUnguessableVariable", "anotherUnguessableVariable");
            session_start();
            if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){
                header ("Location: login.php");
            }

            include "system/config.php";

            $pageURL = basename($_SERVER["REQUEST_URI"]);
            $pageName = pathinfo(parse_url($pageURL, PHP_URL_PATH), PATHINFO_FILENAME); 

            $selectedLang = $_GET["lang"];
                if(!isset($selectedLang)){
                    $selectedLang = "de";
                }
            $langURL = "?lang=" . $selectedLang;

            $conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
            $conn->set_charset("utf8");
            if($conn->connect_error){
                die("Connection failed: " . $conn->connect_error);
            } 
            // fetch main translations
            $location = "%main%";
            $stmt = $conn->prepare("SELECT tID, " . $selectedLang . " FROM TranslationsMain WHERE location LIKE ? ORDER BY tID");
            $stmt->bind_param("s", $location);
            $stmt->execute();
            $result = $stmt->get_result();  
            while($arrTranslations = $result->fetch_assoc()){
                $trans[] = array("ID" => $arrTranslations["tID"], "trans" => $arrTranslations[$selectedLang]);
            }
            $conn->close();

            // get main translations by ID
            function fetchTransMain($trans, $itemID){
                foreach($trans as $key => $val){
                    if($val["ID"] == $itemID){
                        return $val["trans"];
                    }
                }
            }
        ?>

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="author" content="Some author" />
        <meta name="description" content="Created: 2015-06" />

        <base href="http://www.myurl.de" target="_self" />

        <title>Some title</title>

        <!-- CSS -->        
        <link rel="stylesheet" type="text/css" href="includes/styles.css" />
        <!-- CSS - Font Awesome -->
        <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />

        <!-- include favicon -->
        <link rel="shortcut icon" href="images/favicon/favicon.ico" type="image/x-icon" />
        <link rel="icon" href="images/favicon/favicon.png" type="image/png" />
        <link rel="icon" sizes="32x32" href="images/favicon/favicon-32.png" type="image/png" />
        <link rel="icon" sizes="64x64" href="images/favicon/favicon-64.png" type="image/png" />
        <link rel="icon" sizes="96x96" href="images/favicon/favicon-96.png" type="image/png" />
        <link rel="icon" sizes="196x196" href="images/favicon/favicon-196.png" type="image/png" />
        <link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-touch-icon.png" />
        <link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-touch-icon-60x60.png" />
        <link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-touch-icon-76x76.png" />
        <link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-touch-icon-114x114.png" />
        <link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-touch-icon-120x120.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-touch-icon-144x144.png" />
        <meta name="msapplication-TileImage" content="favicon-144.png" />
        <meta name="msapplication-TileColor" content="#ffffff" />

        <script>
            var baseURL = '<?php echo $baseURL; ?>';
            var pageURL = '<?php echo $pageURL; ?>';
            var pageName = '<?php echo $pageName; ?>';
            var selectedLang = '<?php echo $selectedLang; ?>';
        </script>
    </head>   
    <body>

Now this is not working and I think I am probably missing a couple of things but I couldn't find a good tutorial or guideline on that. Also, I am not sure if there is anything else I need to do in order to start and set up the session.

现在这不起作用,我想我可能遗漏了一些东西,但我找不到一个好的教程或指南。另外,我不确定是否还有什么我需要做才能开始和设置会话。

Can someone help me with this ?

有人可以帮我弄这个吗 ?

Note:
This is only about checking if a user is already logged in since all the actual user registration and verification is done on the separate login page and for this I already have the code working.

注意:
这只是关于检查用户是否已经登录,因为所有实际的用户注册和验证都是在单独的登录页面上完成的,为此我已经有代码工作。

Update:Enabling error messages returns the following errors:

更新:启用错误消息会返回以下错误:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 9

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 9
array(0) { } 
Warning: Cannot modify header information - headers already sent by (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 12

Notice: Undefined index: lang in /homepages/21/d580042014/htdocs/includes/header.php on line 18

Update:
As per the comments I now posted everything that's currently in the header.

更新:
根据评论,我现在发布了当前在标题中的所有内容。

Many thanks in advance.

提前谢谢了。

回答by Funk Forty Niner

Update: The question has been resolved in chat.

更新:该问题已在chat 中解决。



As per your edit, change this block:

根据您的编辑,更改此块:

<!DOCTYPE html>
<html>
    <head>
        <?php 
            define("someUnguessableVariable", "anotherUnguessableVariable");
            session_start();
            if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){
                header ("Location: login.php");
            }

to:

到:

<?php 
session_start();
?>

<!DOCTYPE html>
<html>
    <head>
        <?php 
            define("someUnguessableVariable", "anotherUnguessableVariable");

            if(!isset($_SESSION['login']) && $_SESSION['login'] != ''){
                header ("Location: login.php");
                exit; // stop further executing, very important
            }
  • Follow the same structure for starting the session in all your files using sessions.
  • Make sure that your file does not have a byte order mark (BOM).
  • No space before <?phpetc. this has already been established in comments.
  • 使用会话在所有文件中按照相同的结构启动会话。
  • 确保您的文件没有字节顺序标记 (BOM)。
  • 之前没有空间<?php等等。这已经在评论中建立了。

Using a code editor such as Notepad++ https://notepad-plus-plus.org/and to save it as UTF-8 without BOM which will ensure there is no byte order mark.

使用 Notepad++ 等代码编辑器https://notepad-plus-plus.org/并将其保存为没有 BOM 的 UTF-8,这将确保没有字节顺序标记。

Also, using the new method for your sessions array check.

此外,使用新方法进行会话数组检查。

if(!isset($_SESSION['login']) && $_SESSION['login'] != ''){

Also check to see that none of your included/required files have the same issues, including login.php.

还要检查您的包含/必需文件是否有相同的问题,包括login.php.



Footnotes:

脚注:

Inside Notepad++'s dropdown menu, you will see

在 Notepad++ 的下拉菜单中,您将看到

  • Encoding. It will show you what the present file's encoding is set to.
  • 编码。它将显示当前文件的编码设置为什么。

If it does show a byte order mark, follow these steps:

如果它确实显示了字节顺序标记,请按照下列步骤操作:

  1. Click on "Encoding".
  2. Convert to UTF-8 without BOM
  3. Save the file.

    • Do this for all your files.
  1. 点击“编码”。
  2. 不带 BOM 转换为 UTF-8
  3. 保存文件。

    • 对所有文件执行此操作。


Reference(s):

参考):



Sidenote:

边注:

You should change $stmt->execute();to

你应该$stmt->execute();改为

if(!$stmt->execute()){
    trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}
  • It's better to catch possible errors in your query.
  • 最好在查询中捕获可能的错误。

回答by petebolduc

You need to move

你需要移动

session_start();
if((!isset($_SESSION['login']) && $_SESSION['login'] != '')){
    header ("Location: login.php");
}

to the top of the scrip and move !inside the bracket.

到纸片的顶部并!在支架内移动。

回答by Onimusha

The following portion should go before include "system/config.php";because it seems like this file is outputting and also the fact that the following code is not dependant on any other data.

下面的部分应该include "system/config.php";放在前面,因为这个文件似乎正在输出,而且下面的代码不依赖于任何其他数据。

session_start();
if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){
    header ("Location: login.php");
}

Second:

第二:

if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){

if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){

Should probably be: if(!isset($_SESSION['login']) && $_SESSION['login'] == ''){

应该是: if(!isset($_SESSION['login']) && $_SESSION['login'] == ''){

meaning == ''and not != ''

意义== ''而不是!= ''

A user not logged in will most likely (depending on your code) not have a value set so your code will check to see if it's not blank so only logged in users will get forwarded.

未登录的用户很可能(取决于您的代码)没有设置值,因此您的代码将检查它是否不为空,因此只有登录的用户才会被转发。

Hence:

因此:

<?php
define("someUnguessableValue", "anotherUnguessableValue");
session_start();
if(!isset($_SESSION['login']) && $_SESSION['login'] == ''){
    header("location:login.php");
}

include "system/config.php";
//.... the rest
?>
<!DOCTYPE html>
<html>
    <head>

If it's not forwarding, then $_SESSION['login'] is most likely set, you need to clear your cookies for that domain.

如果不是转发,则很可能设置了 $_SESSION['login'],您需要清除该域的 cookie。

回答by Luca

Put the user profile in session variables in PHP script you call after the login page

将用户配置文件放在登录页面后调用的 PHP 脚本中的会话变量中

$_SESSION['user_id'] = $row["user_id"];
$_SESSION['profile_id'] = $row["profile_id"];
$_SESSION['name'] = $row["name"];
$_SESSION['surname'] = $row["surname"];
$_SESSION['application_auth'] = $row["application_auth"];

Put the following code at the top of each page you want to protect by not valid users

将以下代码放在您要保护无效用户的每个页面的顶部

<?php 
include("sessionCheck.php");
?>

The sessionCheck script In this case I also check if the user is entitled to view the specific page using the profile_id but you can remove it

sessionCheck 脚本在这种情况下,我还检查用户是否有权使用 profile_id 查看特定页面,但您可以将其删除

<?php
    session_start();
    if(!IsSet($_SESSION['user_id']) or $_SESSION['profile_id'] !=1)
    {
        header("location: http://www.yourdomain.com/login.php?message=Invalid user");
    }   
?>