【发布时间】:2013-10-08 08:24:12
【问题描述】:
目标
仅为经过身份验证的用户提供库存管理功能。
问题
当我使用我的 jQuery 登录对话框伪造登录并单击 [连接] 时,没有输入任何凭据,Javascript 警报显示我已通过身份验证。
当我导航到库存部分时,我看不到任何管理按钮。没关系,但是为什么 PHP 会返回经过身份验证的用户呢?
当我正确验证时,Javascript 警报仍然显示我已通过验证,但在页面刷新后我看不到任何管理按钮。怎么了?
代码示例
网站的入口点:index.php
<?php
require_once "security/logout.php";
logout();
session_start();
$now = time();
$_SESSION["authenticated"] = false;
$_SESSION["expires"] = $now + strtotime("20 minutes");
$_SESSION["last_activity"] = $now;
?>
logout.php
<?php
function logout() {
$sid = session_id();
if (empty($sid)) session_start();
session_unset();
session_destroy();
session_write_close();
session_regenerate_id(true);
}
?>
authenticated.php
该文件用作require_once,用于每个需要设置会话的php 文件。有点像对每个 PHP 文件使用 session_start()。
<?php
require_once "security/logout.php";
$sid = session_id();
if (empty($sid)) session_start();
if (!isSet($_SESSION["expires"])
|| !isSet($_SESSION["authenticated"])
|| !isSet($_SESSION["last_activity"])
|| $_SESSION["expires"] < time()) {
logout();
$now = time();
$_SESSION["authenticated"] = false;
$_SESSION["last_activity"] = $now;
$_SESSION["expires"] = $now + strtotime("20 minutes");
}
?>
login.php
<?php
require_once "security/authenticated.php";
require_once "data/data_access.php";
$userName = "";
$password = "";
if (isSet($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isSet($_REQUEST["password"])) $password = $_REQUEST["password"];
if (isAuthenticUser($userName, $password)) {
session_regenerate_id(true);
$now = time();
$_SESSION["authenticated"] = true;
$_SESSION["last_activity"] = $now;
$_SESSION["expires"] = $now + strtotime("20 minutes");
} else $_SESSION["authenticated"] = false;
// The line below is the server response reported by the Javascript alert().
echo $_SESSION["authenticated"] ? 'true' : 'false';
?>
编辑#1添加了
data/data_access.php
function isAuthenticUser($userName, $password) {
$sql = "select password from jmsports.users where login = :login";
$cnx = createAndOpenDatabaseConnection();
$stmt = $cnx->prepare($sql);
$stmt->bindParam(":login", $userName);
$stmt->execute();
$result = $stmt->fetch();
$isAuthentic = $result["password"] === $password;
// Bool:strictBool only ensures that only true or false is returned.
return Bool::strictBool($isAuthentic);
}
EDIT #2添加了在服务器端显示/隐藏按钮的代码。
inventory-section.php
// This line below states that my authenticated session variable is false.
file_put_contents("debug.txt", $_SESSION["authenticated"] ? "true" : "false", FILE_APPEND);
<div id="newButtonDiv" style="text-align: center;">
<?php if ($_SESSION["authenticated"]): ?>
<button id="newButton">Add New Item</button>
<?php endif; ?>
</div>
任何帮助表示赞赏。谢谢!
【问题讨论】:
-
你能发布 data/data_access.php 吗?假设 isAuthenticUser() 在其中...
-
刚刚使用
data/data_access.php中包含的isAuthentic()函数编辑了我的问题。 -
=--edit- 复制到主评论 - 抱歉,不喜欢 cmets 中的代码块... :(
标签: php session authentication session-variables