我有两个我在下面抽象的PHP文件: 文件1:login.php
<?
ob_start();
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 1) { // A match was made.
// Register the values & redirect:
$_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
文件2:CustomIndex.php
<?
ob_start();
session_start();
if (empty($_SESSION['user_first_name'])) {
if(isset($_GET['custom2'])){
$url = BASE_URL . '/index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
sleep(5);
$url = BASE_URL . "/CustomIndex.php?custom2=1";
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if(isset($_SESSION['user_first_name'])){
// …program code…
}
?>
当执行FILE 1(login.php)时,可能有10%的时间“FILE 2(CustomIndesx.php)中的if(空($ _ SESSION ['user_first_name']))”语句为真,并且客户端被重定向到index.php而不是被执行,就像没有设置$ _SESSION变量一样。
然而,在那之后,如果我直接运行FILE 2(CustomIndesx.php),它会读取$ _SESSION数据并正确执行。
我在“SLEEP”之后添加了所有代码以模拟手动运行CustomIndesx.php,但除了将重定向延迟5秒之外,没有任何改变。
任何人都可以提出这种随机行为的原因,以及如何消除它?
答案 0 :(得分:0)
1)重要的是:session_start()
必须是两个页面中的第一个代码行。如果没有,则在完成每个页面脚本的运行后会话将关闭。
查看
中发生的事情 2)然后,在login.php
代码部分:
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
您正在与session_write_close()
进行会话并关闭它。然后,在CustomIndex.php中,您尝试再次打开它。它似乎与打开的会话ID不同。因此,请尝试删除session_write_close();
行并再次测试。
<强>的login.php:强>
<?php
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) > 0) {
$_SESSION = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php';
header("Location: $url");
exit();
}
?>
<强> CustomIndex.php:强>
<?php
session_start();
if (!isset($_SESSION['user_first_name']) || empty($_SESSION['user_first_name'])) {
echo 'SESSION USER_FIRST_NAME IS NOT SET!';
} else {
echo 'SESSION USER_FIRST_NAME IS OK: ' . $_SESSION['user_first_name'];
}
?>