PHP:$ _SESSION似乎没有设置.任何的想法?

Wil*_*ler 2 php authentication ajax session jquery

我在搜索为什么我的会话不会被设置时通过这个SO Q/A.

On $_GET set $_SESSION won't work

我真的不明白这是否适用于我的情况.在这里.

的index.php

<?php 
session_start();

if (!isset($_SESSION["authenticated"])) $_SESSION["authenticated"] = false; 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
...
Run Code Online (Sandbox Code Playgroud)

然后,当用户验证自己时,我会调用以下内容.

authenticate.php

<?php
require_once "data/data_access.php";

$userName = "";
$password = "";

if (isset($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isset($_REQUEST["password"])) $password = $_REQUEST["password"];

$isAuthentic = isAuthenticUser($userName, $password);
$_SESSION["authenticated"] = $isAuthentic;
echo $isAuthentic;
?>
Run Code Online (Sandbox Code Playgroud)

我还每隔5秒检查一次身份验证事件,以便为用户所在的部分创建按钮.

authenticated.php

<?php echo isset($_SESSION["authenticated"]) && $_SESSION != false ? 'true' : 'false'; ?>
Run Code Online (Sandbox Code Playgroud)

和我的Ajax调用设置:

my_project.js

$(document).ready(function() { startAuthenticationChecking(); });

function startAuthenticationChecking() { 
    setInterval(function() { ajaxSession("authenticated.php"); }, 5000);
}

function ajaxSession(actionURL) {
    var authenticated = false;
    $.ajax({
        async: false,
        url: actionURL,
        success: function(authenticated) {
            alert(authenticated);
            if (authenticated) {
                if (("#addNewAtvButtonDiv").is(":empty"))
                    $("#addNewAtvButtonDiv").add("<button id='newAtvButton'>Inscrire un nouveau VTT en inventaire</button>");
                if (("#addNewSledButtonDiv").is(":empty"))
                    $("#addNewSledButtonDiv").add("<button id='newSledButton'>Inscrire un nouvel UTT en inventaire</button>");
                if (("#addNewUtvButtonDiv").is(":empty"))
                    $("#addNewUtvButtonDiv").add("<button id='newUtvButton'>Inscrire une nouvelle motoneige</button>");
                $("button").button();
            } else {
                $("#addNewAtvButtonDiv").children().remove();
                $("#addNewSledButtonDiv").children().remove();
                $("#addNewUtvButtonDiv").children().remove();
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我的问题

虽然我在问$_SESSION["authenticated"] = false之后session_start();,当ajaxSession()询问用户是否通过身份验证时authenticated.php,它总是返回'false'.使用authenticate.php正确的凭据进行身份验证后的事件.

相关问题: PHP / Ajax : How to show/hide DIV on $_SESSION variable value?

欢迎任何帮助!我最近几天晚上都在研究这个问题,现在还在.

谢谢!

Dan*_*ell 5

确保在任何输出之前$_SESSIONsession_start();声明所有使用变量的页面.

它看起来像authenticate.php没有session_start();声明,但在下面使用会话请求.

$ _SESSION ["authenticated"] = $ isAuthentic;

除非您已包含/需要文件authenticate.php,并且父文件已session_start();声明,否则这将导致问题.

注意:

在session_start(); 将创建会话或恢复会话.每个使用会话变量的页面都需要它.

php.net

session_start()根据通过GET或POST请求传递的会话标识符创建会话或恢复当前会话,或通过cookie传递.