我是PHP新手,在会话方面更像是初学者。我有我的index.php页面,这是用户可以注册和登录的地方。这些表单分别发布到validate.php和loginvalidate.php页面,用于注册和登录。
加载时我在index.php上有这些错误:
1)注意:未定义的索引:已注册 2)注意:未定义的索引:从未使用过
我尝试过多方面修改我的文字,但我从来没有解决过错误。
的index.php
<?php
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
?>
Validate.php(提交注册表后)
if (mysqli_num_rows($result) > 0) { //IF THERE IS A PASSWORD FOR THAT EMAIL IN DATABASE
$_SESSION['registered'] = "Email is already registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Loginvalidate.php(提交登录表单后)
if ($numrows!=0) //IF THERE IS A PASSWORD FOR THAT EMAIL IN THE DATABASE
{
if ($row['password'] == $password) { //IF THE PASSWORD MATCHES USER INPUT
header('Location: homepage.php');
echo "lol";
exit();
}
else{
$_SESSION['badlogin'] = "Email/password combination not valid.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
}
else { //THERE IS NO PASSWORD FOR THAT EMAIL, SO THAT EMAIL IS NOT REGISTERED
$_SESSION['neverused'] = "Email is not registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
好的,所以我的脚本完成了它的目的。我唯一无法解决的是这些会话错误。你有没有看到滥用会话?当然,我已经在所有.php文件中启动了会话。
另外,请注意,我知道没有黑客的保护。这仅适用于未包含任何重要数据的未来原型。
答案 0 :(得分:16)
出现这些错误的原因是您正在尝试读取不存在的数组键。 isset()函数在那里,您可以测试它。对于每个元素,如下所示的东西将起作用;您不需要空检查,因为您从不为元素指定null:
// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {
// it does; output the message
echo $_SESSION['registered'];
// remove the key so we don't keep outputting the message
unset($_SESSION['registered']);
}
您也可以在循环中使用它:
$keys = array('registered', 'badlogin', 'neverused');
//iterate over the keys to test
foreach($keys as $key) {
// test if $key exists in the $_SESSION global array
if (isset($_SESSION[$key])) {
// it does; output the value
echo $_SESSION[$key];
// remove the key so we don't keep outputting the message
unset($_SESSION[$key]);
}
}
答案 1 :(得分:4)
如果您收到未定义的索引错误,您可以尝试确保在尝试比较值之前设置了索引。请在此处查看isset函数的文档: http://php.net/manual/en/function.isset.php
if (isset($_SESSION['registered']))
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
}
if (isset($_SESSION['badlogin']))
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
}
if (isset($_SESSION['neverused']))
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
}