-2

OK so I am making it to where when the user logs out and they try to go back to the member page it says you must be logged in to veiw this page well the echo is displaying that they must be logged in and its keeping them out but there is an error. Here is the page. it says there is a problem on line 5.

MEMBER PHP PAGE

<?php

session_start();

if ($_SESSION['username'])
    echo "Welcome, ".$_SESSION['username']."!<br /><a href='logout.php'>Logout</a>";
else
    die("You must be logged in!");
?>
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • Don't delete your content, there are already two notifications that this is a duplicate. By leaving the content in its place it's easier for people who coma across this question to determine whether or not this applies to them. – Jeroen Vannevel Dec 11 '13 at 17:01

3 Answers3

0
<?php

session_start();

if (isset($_SESSION['username']))
echo "Welcome, ".$_SESSION['username']."!<br /><a href='logout.php'>Logout</a>";
else
die("You must be logged in!");
?>
Zword
  • 6,605
  • 3
  • 27
  • 52
0

Improve value checking for the if clause. I like to do an array_key_exists as well as a !empty(trim()) to ensure the value is set:

session_start();

if (array_key_exists('username', $_SESSION)) && !empty(trim($_SESSION['username']))) {
    echo "Welcome, " . $_SESSION['username'] . "!<br /><a href='logout.php'>Logout</a>";
}
else {
    die("You must be logged in!");
}
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
  • what if `$_SESSION['username'] = 0` ? `empty()` check will fail. – Raptor Dec 04 '13 at 02:48
  • That’s an extra level of validation the original poster should pursue based on their username logic. The question is about the index missing error. – Giacomo1968 Dec 04 '13 at 02:51
0

To avoid Undefined Index error, you can use isset() to check :

session_start();
if (isset($_SESSION['username']) && trim($_SESSION['username']) != '') {
    echo 'Welcome, ' . $_SESSION['username'] . '!<br /><a href="logout.php">Logout</a>';
} else {
    die("You must be logged in!");
}

Side note: Assuming these lines are the first few lines of the file, if you print HTML code without HTML head and body, the page is incomplete & browsers may complain about HTML structure. Suggest to have at least minimal HTML structure for every page on screen.

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • 2
    I generally recommend keeping PHP and HTML (or any presentation) separate with a templating setup for that very reason. Then PHP pages don't output html, and it solves issues like malformed html structure, output before trying a headers command, etc. – JC. Dec 04 '13 at 02:56
  • Agree. However, it needs extra coding work. – Raptor Dec 04 '13 at 02:58