我正在使用 PHP 身份验证系统来登录用户。登录用户可以正常工作,但是,在刷新页面(在任何页面上)时,会话变量会重置并且用户被“注销”。我在每个页面上都使用 session_start() 。我有文件 auth.php 和 authenticate.php 来记录和验证用户。这是一个令人沮丧的问题,我们将不胜感激。我在这里给你代码:
auth.php:
<?php
function credentials_valid($email, $password) {
$email = mysql_real_escape_string($email);
$query = "SELECT `id`, `salt`, `password`
FROM `#######`
WHERE `email` = '$email' ";
$result = mysql_query($query);
if(mysql_num_rows($result)) {
$user = mysql_fetch_assoc($result);
$password_requested = sha1($user['salt'] . $password);
if($password_requested === $user['password']) {
return $user['id'];
}
}
return false;
}
//logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
//Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user) {
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `#######`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
//Requires a current user
function require_login() {
if(!current_user()){
$_SESSION['redirect_to'] = $_SERVER["REQUEST_URI"];
header("Location: index.php");
exit("You must log in.");
}
}
?>
验证.php:
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_SESSION['redirect_to']){
header("Location: " . $_SESSION['redirect_to']);
unset($_SESSION['redirect_to']);
}else{
header("Location: index.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
在我的一个用户登录的页面上,我在 php 标头中有这个:
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
if(isset($_GET["logout"]) && $_GET["logout"]==1)
{
//User clicked logout button, distroy all session variables.
session_destroy();
header('Location: '.$return_url);
}
?>
系统不稳定。有时,如果我在登录后立即刷新页面,会话变量将立即被销毁。其他时候,用户将在连续几次刷新后保持登录状态。请让我知道您看到了什么问题。谢谢!