'Sign In or Sign Out menu options not working in PHP script
All the page scripts (i.e. .php files) in my application use the "include" statement to include a menu (menu.php) on the page as follows:
<div id="menublock" class="menu">
<ul class="clearfix">
<li><a href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></l1>
<li><a href="Membership">Membership</a></l1>
<li><a href="gallery.php">Gallery</a></li>
<?php
if (isset($_SESSION['valid_user'])) {
echo '<li><a href="logout.php">Sign Out</a></li>';
} else {
echo '<li><a href="login.php">Sign In</a></li>';
}
?>
</ul>
</div>
<!-- end of menublock -->
The session variable "valid_user" indicates whether the user is logged in or not, and the final option on the menu should reflect this by showing either "Sign In" or "Sign Out".
The login.php and logout.php scripts, after performing their functions, will call themselves and display a message indicating that the user is now logged in or out. However, the menu shows the wrong option. For example, when you sign out the menu will still show the "Sign Out" option. If you then click on one of the other menu options the relevant page is shown with the correct "sign In" option.
Here is logout.php in response to Levi's request. Inserting it has made me realize what the problem is. The php code in menu.php is executed before the logout request is processed, so the valid_user session variable still indicates that the user is logged in. A similar thing no doubt happens in login.php. Silly mistake, I know!
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php
include( 'assnid.html' );
?>
</head>
<body>
<?php
include( 'menu.php' );
include( 'functions.php');
$db = dbconnect();
$temp = logAction( $db, 'Sign Out' );
$db->close();
?>
<div id="bodytext">
<!-- Main content -->
<?php
// store to test if they *were* logged in
$old_user = $_SESSION['valid_user'];
unset($_SESSION['valid_user']);
unset($_SESSION['gen_pw']);
session_destroy();
?>
<html>
<body>
<!-- <h2>Sign out</h2> -->
<?php
if (!empty($old_user))
{
echo '<h2>You have been signed out.</h2><br />';
}
else
{
// if they weren't signed in but came to this page somehow
echo '<h2>You were not signed in, and so have not been signed out.</h2><br />';
}
?>
<?php
include 'footer.html';
?>
</div>
</body>
</html>
This is sending me crazy in trying to resolve it, as many websites have similar logic, and I don't understand why this should not work.
Is this something to do with compile opcodes being cached and then retrieved, or is it something else?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
