且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-28 23:28:22

更新:该问题已在根据您的修改,更改此块:

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");
            }

收件人:

<?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
            }

  • 在使用会话的所有文件中遵循相同的结构来启动会话.
  • 确保您的文件没有字节顺序标记(BOM).
  • <?php等之前没有空格.这已在注释中建立.
    • 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 <?php etc. this has already been established in comments.
    • 使用诸如Notepad ++之类的代码编辑器 https://notepad-plus-plus.org/并将其保存为不带BOM的UTF-8,这将确保没有字节顺序标记.

      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.

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

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

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

还要检查以确保没有任何包含/必需的文件具有相同的问题,包括login.php.

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

脚注:

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

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

  • 编码.它将显示当前文件的编码设置.

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

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

  1. 单击编码".
  2. 转换为不带BOM的UTF-8
  3. 保存文件.

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

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


参考文献:


Reference(s):

旁注:

您应将$stmt->execute();更改为

if(!$stmt->execute()){
    trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}

  • ***在查询中捕获可能的错误.