phpissetundefined-index

undefined index error with isset() in place?


Have I missed something here that I'm not seeing that would throw an undefined index error for this code? In testing a addition of code to functions.php where $_POST['sub'] is not being passed it throws the undefined index error below, but this same isset() test against the exact same POST variable "sub" is performed about 12 times above line 494 without throwing error. What am i missing?

ERROR FROM PHP

Notice: Undefined index: sub in /home/path/public_html/dtest/includes/functions.php on line 494

CODE FOR LINE 494

if (isset($_POST['sub']) && $_POST['sub'] == "ritem") {
    $id = $_POST['ritemid'];
    unset($_SESSION['cart']['items'][$id]);
    header("Location: ".$_SERVER['HTTP_REFERER']."");
    die();
} else {
    echo $_POST['sub'];
}

Solution

  • Remove the echo $_POST['sub']; from the else part which is responsible for this Undefined index notice and replace with the echo statement.

    Should be like this..

    <?php
    
    if (isset($_POST['sub']) && $_POST['sub']=="ritem") {
        $id=$_POST['ritemid'];
        unset ($_SESSION['cart']['items'][$id]);
        header("Location: ".$_SERVER['HTTP_REFERER']."");die();}
    else
    {
     echo "The subject is not set";    
    }
    

    That is because.. when the if fails which means the $_POST['sub'] is not set , so when it comes to the else part , you are trying to output $_POST['sub'] which was actually not set (which is actual source of this problem)