Undefined Index with PHP Sessions

Undefined index with PHP sessions

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

How to resolve Undefined index error in PHP

try below where you are displaying the menu

<nav>
<a id="mainpage">Main Page</a>
<?php if (!isset($_SESSION['logged_in'])) { ?>
<a href="login2.php">Login</a>
<a href="register.php">Register</a>
<?php } else { ?>
<a href="post.php">Posting</a>
<a href="#">Members posts</a>
<a href="logout.php" class="outbutton">Logout</a>
<?php } ?>

Notice: Undefined index when trying to read $_SESSION array

Use isset() function:

if(isset($_SESSION["previouspage"])) {
echo "<a href=".$_SESSION["previouspage"].">Go back.</a>";
$_SESSION["previouspage"] = "index.php";
}else {
//No go back button will be displayed.
$_SESSION["previouspage"] = "index.php";
}

Undefined index' error for session - php

You are no checking if "login_user_admin" exist in $_SESSION or not. Change $user_check = $_SESSION['login_user_admin']; to this one

if(isset($_SESSION['login_user_admin'])){
$user_check = $_SESSION['login_user_admin'];
}else{
$user_check = null;
}

You can always check if index exist in $_SESSION using isset. When you try to get value from $_SESSION and that index does not exist in $_SESSION, script raises a notice error, which is sometime hidden due to your error settings

if(isset($_SESSION['login_user_admin'])){
$user_check = $_SESSION['login_user_admin'];
$sql = "select name,img from users where type = 'admin' AND username='$user_check'";
$result = $connection->query($sql);
$row = $result->fetch_assoc();
$name = $row['name'];
$img = $row['img'];
}else{
$img = null;
}

Undefined index in session

Check if it is set first in index.php

if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
}


Related Topics



Leave a reply



Submit