Undefined index with PHP sessions

后端 未结 2 1469
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 12:12

I\'m new to PHP and am even more of a beginner when it comes to sessions. I have my index.php page, which is where users can register and login. The forms are posting to val

相关标签:
2条回答
  • 2020-11-29 13:02

    The reason for these errors is that you're trying to read an array key that doesn't exist. The isset() function is there so you can test for this. Something like the following for each element will work a treat; there's no need for null checks as you never assign null to an element:

    // 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']);
    }
    

    You could also use it in a loop:

    $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]);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 13:08

    If you're getting undefined index errors, you might try making sure that your indexes are set before you try comparing the values. See the documentation for the isset function here: 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'];                    
      }
    }
    
    0 讨论(0)
提交回复
热议问题