harishk harishk - 8 months ago 49
PHP Question

PHP index pages gives out session unknown error when logged out

I have a login and logout session for my index page.

So, it uses the email of user as session, and when user logs in, it gets the details from fb using his email which is stored in session.

But when the user logs out, it shows an error of


Notice: Undefined index: email in D:\xampp\htdocs\site\index.php


My code goes as:

<?php
//15 2 2015
session_start();
?>
<?php
$email = $_SESSION['email'];
$sql = "SELECT * FROM landlords WHERE email = '$email' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<?php
echo '<li class="dropdown submenu">';
echo '<a href="#" class="dropdown-toggle">'; echo ($row["name"]); echo '</a>';
echo '<ul class="dropdown-menu">';
echo '<li><a href="myaccount.php">My Account</a></li>';
echo '<li><a href="logout.php">Log Out</a></li>';
echo '</ul>';
echo '</li>';
?>
<?php }
} else {
echo '<li> <a href="signin.php"><span class="icon-user"></span>Sign In</a></li>';
}
?>


Ignore the multiple php openings.

So, when a user logs in, it works fine, but when a user logs out, it gives a error of


Notice: Undefined index: email in D:\xampp\htdocs\site\index.php


Any help is appreciated.

Answer Source

The issue is that you don't guard the situation where the email session var is unset, as is after session unset (logout). Try this:

$email = @$_SESSION['email'];
if (!empty($email)) {
    $sql = "SELECT * FROM landlords WHERE email = '$email' ";
    $result = $conn->query($sql);
}
if (isset($result) && $result->num_rows > 0) {

...