我有一个名为 login.php 的脚本,该脚本获取通过表单提供的用户信息,并检查输入的登录信息是否有效。如果信息无效,则调用以下代码:
$GLOBALS['user_login_fail'] = true;
header('Location: ../index.php'); //this displays index.html
在 index.html 中,如果用户输入了无效的登录信息,则会显示一条错误消息:
<?php
if($GLOBALS['user_login_fail'] == true)
{
echo '<div> Login credentials could not be verified </div>';
}
else
{
echo "no error";
}
?>
然而,在重定向后,我收到一个错误:注意:未定义的索引:user_login_fail 。这有什么不对?
答案 0 :(得分:2)
我认为你让全局变量和会话变量混淆了。
Globals存在于当前范围内的任何位置,但浏览器重定向会创建新范围。 Session variables在浏览器重定向中保持不变。
试试这个:
session_start();
$_SESSION['user_login_fail'] = true;
和
session_start();
if(isset($_SESSION['user_login_fail']) && $_SESSION['user_login_fail']) {
echo '<div> Login credentials could not be verified </div>';
} else {
echo "no error";
}
答案 1 :(得分:2)
似乎(如前所述)你在php中将$_GLOBALS
与$_SESSION
混淆。
我马上告诉你: $_GLOBALS
是php的不良做法。
当人们谈论其他语言中的全局变量时,它意味着与PHP中的变量不同。那是因为PHP中的变量并不是真正的全局变量。典型PHP程序的范围是一个HTTP请求。会话变量实际上具有更广泛的PHP“全局”变量范围,因为它们通常包含许多HTTP请求。
基本上你想要使用$_SESSIONS
。这将是这样做的:
作为验证部分:
session_start();
$_SESSION['user_login_fail'] = true;
header("Location: index.php");
并作为 index.php
session_start();
if(isset($_SESSION['user_login_fail']) && $_SESSION['user_login_fail'] == TRUE) {
echo '<div> Login credentials could not be verified </div>';
} else {
echo "no error";
}