【问题标题】:How to route the user to the client portal using PHP如何使用 PHP 将用户路由到客户端门户
【发布时间】:2019-10-29 23:57:37
【问题描述】:

如果用户在登录后转到 login.html,我会尝试将用户路由到 client_portal.php。

  • 尝试创建包含会话信息的第三个 .php 文件并测试是否设置了 login_user

  • 尝试使用 jQuery "window.location.replace();"每次自动路由用户

这是来自第三个 PHP 文件 checkLogin.php 的代码

include("session.php");

    if (isset($_SESSION['login_user'])) {
        header("Location: client_portal.php");
        die();
    }

这是来自 session.php -- DB 是实际信息的占位符(这是私有的)

    $link = mysqli_connect('DB', 'DB', 'DB', 'DB'); //Connect to the database

    session_start();    

    //Preparing the SQL statements
    $stmt1 = mysqli_prepare($link,"SELECT username, first_name FROM login WHERE username =?");

    //Binding the SQL statements
    mysqli_stmt_bind_param($stmt1, "s", $user_check);

    $user_check = $_SESSION['login_user']; //Checking if the user has a login session active
    mysqli_stmt_execute($stmt1);

    $result = mysqli_stmt_get_result($stmt1); //Get the result

    $row = mysqli_fetch_assoc($result); //Setting the array

    $_SESSION["login_session"] = $row['username']; //Setting a session under the username
    $firstName = $row["first_name"];

    if(!isset($_SESSION['login_user'])) {
        header("Location: /login");
        die();
    } 

预期:将用户路由到客户端门户 实际:正常加载登录页面

【问题讨论】:

  • 应该是header("Location: client_portal.php"); 没有:

标签: php jquery session login


【解决方案1】:

您错误地设置了会话变量。 这是正确的方法。

$_SESSION['login_session'] = $row['username']; //Setting a session under the username

【讨论】:

  • 我在checkLogin.php中更改了PHP,但登录时仍然没有响应,然后再改回login.html
  • 在 session.php 下,您错误地设置了 Session 变量。我已经编辑了我的答案。它应该是 $_SESSION['login_session'] = $row['username']; //在用户名下设置会话
【解决方案2】:

我想我会发布我的答案,以防有人想在他们的项目中使用它:loggedIn.php

$link = mysqli_connect('DB', 'DB', 'DB', 'DB'); //Connect to the database

    if (!$link) { 
        die('Could not connect: ' . mysqli_connect_error()); 
    }

    session_start();

    $stmt = mysqli_prepare($link,"SELECT logged_in FROM login WHERE username=?");
    mysqli_stmt_bind_param($stmt, "s", $user_check);

    if(!isset($_SESSION['login_user'])) { //Checking if the session is not set
        $user_check = ""; //Make the $user_check null
    } else { //if
        $user_check = $_SESSION['login_user'];
    }

    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);

    $loggedIn = $row["logged_in"];

主登录页面:

    include("loggedIn.php");

    if ($loggedIn == 1) {
        header("Location: client_portal.php");
        die();
    }

【讨论】:

    【解决方案3】:

    您可以为应用创建middlewares,例如用于登录检查权限的中间件。

    这是关于什么是中间件What is middleware in laravel?的答案

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 2016-07-22
      • 2013-06-12
      • 2021-01-13
      相关资源
      最近更新 更多