如果会话为空,如何使用户返回login.html?

时间:2019-07-23 23:52:03

标签: javascript php html

如果会话为空,是否可以用php文件重定向用户?

例如此代码:

pSession.php

<?php
   include('pConfig.php');
   session_start();

   $user_check = $_SESSION['login_user'];

   $ses_sql = mysqli_query($db,"select UserName from userinfo where UserName = '$user_check' ");

   $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

   $login_session = $row['UserName'];

   if(!isset($_SESSION['login_user'])){
      header("Location: ../login3.html");
      die();
   }
?>

并在javascript中使用它:

Javascript:

$(document).ready(function () {
    checkSession();
})
function checkSession() {
    $.ajax({
        type: 'POST',
        url: '../srtdash/php/pSession.php',
        dataType: 'json',
        data: '',
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
           console.log("Welcome to Credit Investigation");
        },
        error: function (error) {
            console.log(JSON.stringify(error));
        }
    });
}

HTML:

<script type="text/javascript" src="../srtdash/jsScripts/jsIndex.js"></script>

如果用户实际已登录,我是否正确执行重定向?否则,如果用户未登录,如何将用户重定向到login.html?

1 个答案:

答案 0 :(得分:0)

利用

<?php
        include('pConfig.php');
        $username = $_POST['username'];
        $password = $_POST['password'];
        $username = mysqli_real_escape_string($username);
        $password = mysqli_real_escape_string($password);
        $sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
        $result = mysqli_query($sql);
        $count = mysqli_num_rows($result);
        if ($count == 1) {
            session_start();
            $_SESSION['loggedin'] = true;
            $_SESSION['username'] = $username;
        }
        if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
            echo "Welcome to Home page, " . $_SESSION['username'] . "!";
        } else {
            header("Location: ../login3.html");
        }
        ?>