我是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文件中启动了会话。
另外,请注意,我知道并没有受到黑客的保护。这仅用于将来的原型,其中将不包含任何重要数据。
这些错误的原因是您正在尝试读取不存在的数组键。该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]); } }