【发布时间】:2013-10-09 14:17:25
【问题描述】:
我在搜索为什么我的会话无法设置时通过了这个 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>
...
然后,当用户进行身份验证时,我会调用以下内容。
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;
?>
我还每 5 秒检查一次身份验证,以便为用户所在的部分创建按钮。
authenticated.php
<?php echo isset($_SESSION["authenticated"]) && $_SESSION != false ? 'true' : 'false'; ?>
和我的 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();
}
}
});
}
我的问题
虽然我在session_start(); 之后设置了$_SESSION["authenticated"] = false,但当ajaxSession() 询问用户是否通过authenticated.php 进行身份验证时,它总是返回'false'。使用具有正确凭据的 authenticate.php 进行身份验证后的事件。
相关问题:PHP / Ajax : How to show/hide DIV on $_SESSION variable value?
欢迎任何帮助!最近我已经为此工作了几个晚上和几天,现在仍然如此。
谢谢!
【问题讨论】:
-
您是否在每个页面上都运行
session_start();? -
@Nytangel:不,我不知道。只有
index.php可以启动会话。然后,我主要使用Ajax来改变和加载页面上的部分,全部使用$.post()、$.ajax()、$("#div_id").load()等。 -
session_start() 在所有 PHP 页面上都是必需的。如果已经有 cookie 告诉 PHP 存在一个会话,它将正确填充 $_SESSION[]。如果它是一个干净的开始,它将进行初始化。因此,请将 session_start() 放在您拥有的每个 PHP 文件上。
-
确保开启ALL错误报告,看看是否有任何错误。另外,您是否在同一个域上运行所有代码? (有或没有www)
-
@Ken Cheung:我以为
session_start();会简单地重新开始一个新的会话,你知道,这种20 分钟后到期的会话吗?我会照你说的做,并随时通知你。谢谢你的提示! =)
标签: php jquery ajax session authentication