繁体   English   中英

带有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();
    }
}

文件-> 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';
        }
    }
}

文件-> 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(我在每个页面上都添加了包含的代码段)

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

结果为print_r($ _ SESSION);

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

如果登录成功,我将得到“ adminpanel.php”,这是我的页面重定向到的位置。 一切正常,但问题始于adminpanel.php:尽管我使用session_start(),但我的会话变量(如id,用户名,login_string等)却消失了。

我已经阅读了有关asp.net的问题,其中您无法通过ajax传递会话变量。 php是一样的吗? 有办法解决吗?

我已经审查了您的代码。 一切都很完美。 但是问题是当您在“文件-> functions.php-> loginMember($ riziv,$ password)”中分配会话时。 由于您通过ajax请求,因此并非对所有页面都可用。

有两种解决方法,要么成功登录后重新加载页面,要么从“ FILE-> functions.php-> loginMember($ riziv,$ password)”返回值,然后在

“文件-> adminpanel.php”

希望您能从我的回复中获得帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM