使用ajax的PHP登录脚本可以工作,但会话变量不存在


PHP Login script with ajax works but session variables do not exist

在我的网站上,我只使用ajax调用来保存和获取数据。

我还在登录时使用ajax。所以这就是我所做的:

文件->ajaxLogin.js

if (check === true) {
    $.ajax({
        type: 'POST',           
        url: 'PHPCalls.php?CallID=Login',
        data: $("#formLogin").serialize(),
        success: function(data) {                    
            var result = $.trim(data);
            if(result !== 'false') {
                $("#spinner").hide();
                window.location.replace(result);
            }
            else if(result === 'false') {
                $("#spinner").hide();
                alert('No match');
            }
        }
    });
}

文件->PHPCalls.php

if(isset($_GET['CallID']))
{
    //LOGIN
    if ($_GET['CallID'] == 'Login') {
        loginFromForm();
    }
}

FILE->functions.php->loginFromForm()

function loginFromForm() {
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        if(isset($_POST['riziv']) && isset($_POST['password'])) {
            $riziv = htmlentities($_POST['riziv']);
            $password = htmlentities($_POST['password']);
            if (loginMember($riziv, $password) == true) {
                //Login success
                if(isset($_SESSION['oldURL'])) {
                    echo $_SESSION['oldURL'];
                } else {
                    echo 'adminpanel.php';
                }
            } else {
                echo 'false';
            }
        } else { 
            // The correct POST variables were not sent to this page.
            echo 'false';
        }
    }
}

FILE->functions.php->loginMember($riziv,$password)

function loginMember($riziv, $password) {
    // Using prepared statements means that SQL injection is not possible.
    $db = MysqliDb::giveNewDbConnection();
    $data = array('ID', 'Firstname', 'Admin', 'Salt', 'Password');
    $db->where('RIZIV', $riziv);
    if ($result = $db->getOne('tblMember')) {
        $memberID = $result['ID'];
        $firstname = $result['Firstname'];
        $admin = $result['Admin'] = 1 ? true : false;
        $salt = $result['Salt'];
        $db_password = $result['Password'];
        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($db->count == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts
            if (checkBrute($memberID) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $memberID = preg_replace("/[^0-9]+/", "", $memberID);
                    $_SESSION['memberid'] = $memberID;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_'-]+/", "", $firstname);
                    $_SESSION['username'] = $username;
                    $_SESSION['admin'] = $admin;
                    $_SESSION['riziv'] = $riziv;
                    $_SESSION['login_string'] = hash('sha512', $password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $db = MysqliDb::giveNewDbConnection();
                    $data = array("MemberID" => $memberID, "Time" => $now);
                    $db->insert('tblLoginAttempts', $data);
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

FILE->adminpanel.php(我在每一页上都添加了一个include)

<?php
sec_session_start();
if(login_check() == false) {
    header('location: index.php');
}
//redirects to a specific url
if (($_SERVER['REQUEST_URI'] != 'index.php') && ($_SERVER['REQUEST_URI'] != $_SESSION['oldURL'])) {
    $_SESSION['oldURL'] = $_SERVER['REQUEST_URI'];
}
?>
//START THE HTML

FILE->functions.php->sec_session_start()

function sec_session_start() {
    $session_name = 'sec_session_id';
    $secure = false;
    $httponly = true;
    if (ini_set('session.use_only_cookies', 1) == FALSE) {
        header("Location: admin/error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams['lifetime'],
        $cookieParams['path'],
        $cookieParams['domain'],
        $secure,
        $httponly);
    session_name($session_name);
    session_start();
    session_regenerate_id(true);
}

打印结果($_SESSION);

Array
(
    [oldURL] => /hijw/admin/adminpanel.php
)

如果登录成功,我会得到"adminpanel.php",结果是我的页面被重定向到那里。这一切都很好,但问题始于adminpanel.hp:虽然我使用session_start()我的会话变量,如id、username、login_string。。。已经消失。

我读过asp.net的一个问题,在这个问题中,您无法通过ajax传递会话变量。php也是这样吗?有办法解决吗?

我已经审阅了您的代码。一切都很完美。但问题是当您在"FILE->functions.hp->loginMember($riziv,$password)"中分配会话时。它不会对每个页面都可用,因为您是通过ajax请求的。

有两种方法可以解决这个问题,要么在成功登录后重新加载页面,要么从"FILE->functions.hp->loginMember($riziv,$password)"返回值并在中重置会话

"FILE->adminpanel.php"

我希望你能从我的回复中得到帮助。