Link to home
Create AccountLog in
Avatar of Ashraf Hassanein
Ashraf Hassanein

asked on

Php session can not be terminated

I have a web page below  which has a logout button if you click it has to execute the logout.php and if it get back true it has to reload the page.
But whjen reloading the page I have default script which is triggered to check if you are still logged in or not by check the if the $_SESSION['username']  is empty or not, but it is always saying that the username is there,any hint please on how to kill the session?
The Web page is:
<?php
session_start();
?>
<HTML>
<HEAD>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
         <link rel="stylesheet" type="text/css" href="css/main.css">
        <link rel="stylesheet" type="text/css" href="css/jquery.ui.all.css">
        <script type="text/javascript" src="js/jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.10.3.custom.min.js"></script>
</HEAD>
<BODY>
 <div class="header-frame" name="header" id="header">
   <div class="ribbon" id="ribbon">
<strong class="ribbon-content" id="ribbon-content"><img src="../images/logo.gif" alt="mysite" width="150" height="75"></strong>
</div>
<div  id="status-block">
   <label id="logged-username">Username:</label>
   <span id="logged-username-value" class="username"  >
   <br>
   <label id="logged-userIP">Client IP:</label>
   <span id="logged-userIP-value" class="userIP"  >
   <br>
   <label id="logged-priviliges">Role:</label>
   <span id="logged-priviliges-value" class="priviliges"  >
   <br>
   <label id="logged-sesssionDate">Logged On:</label>
   <span id="logged-sesssionDate-value" class="sesssionDate"  >
   <br>
   <label id="logged-sesssionTime">Logged At:</label>
   <span id="-logged-sesssionTime-value" class="sesssionTime"  >
   <br>
</div>
<div id="toolbar-block">
<div id="header-toolbar" class="ui-widget-header ui-corner-all">
<button id="logout">Logout</button>
<button id="settings">Settings</button>
</div>
  <ul id="toolbar-menu" >
    <li><a href="#">Open...</a></li>
    <li><a href="#">Save</a></li>
    <li><a href="#">Delete</a></li>
  </ul>
</div>

                <script>
                 $(function() {
                        var $logout = $("#logout").button({ text: false, icons: { primary: "ui-icon-key" } });
                        var $settings = $("#settings").button({ text: false, icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" } });
                        var $menu = $("#settings").parent().next().show();

                $(document).click(function() {
                        $menu.hide();
                $settings.removeClass("active");
                });
                $logout.click(function() {
                                      $.ajax({
                                              url: 'logout.php', 
                                              type: 'POST',
                                              data: {}, 
                                              success: function(response){
                                             if(response=="true"){
                                               $("#header").load("header.php");
                                               $("#menu").load("menu.php");
                                               $("#main").load("login.php");
                                               }
                                      }
                                      });

                        });
                $settings.click(function(evt) {
                        evt.stopImmediatePropagation();
                        $(this).toggleClass("active")
                        $menu.css("display", $(this).hasClass("active")?"block":"none");
                        $menu.position({ my: "left top", at: "left bottom", of: this });
                        });

                $settings.parent().buttonset().next().hide().menu();

                $menu.hover(function() {
                $(this).addClass("overme");
                }, function() {
                        if($(this).hasClass("overme")) {
                                $(this).hide();
                                $(this).removeClass("overme");
                                $settings.removeClass("active");
                                }
                        });

                $menu.click(function(evt) {
                        alert($(evt.target).text());
                        });
                });
                $.post("check_session.php", {}, function(response){
                    if(response=="true"){
                     var username= <?php echo json_encode($_SESSION['username'], JSON_HEX_TAG); ?>;
                     var userIP= <?php echo json_encode($_SESSION['userIP'], JSON_HEX_TAG); ?>;
                     var priviliges= <?php echo json_encode($_SESSION['priviliges'], JSON_HEX_TAG); ?>;
                     var sesssionDate= <?php echo json_encode($_SESSION['sessionDate'], JSON_HEX_TAG); ?>;
                     var sesssionTime= <?php echo json_encode($_SESSION['sessionTime'], JSON_HEX_TAG); ?>;
                      $("#logged-username-value").html(username);
                      $("#logged-userIP-value").html(userIP);
                      $("#logged-priviliges-value").html(priviliges);
                      $("#logged-sesssionDate-value").html(sesssionDate);
                      $("#logged-sesssionTime-value").html(sesssionTime);
                      $("#status-block").show('show');
                      $("#toolbar-block").show('show');
                     } else {
                      $("#status-block").hide();
                      $("#toolbar-block").hide();
                          }
                });
                </script>
</div>
<div id="bottom"> 
 <div class="menu-frame" name="menu" id="menu">
   menu
 </div>
 <div class="main-frame" name="main" id="main">
   	<div id="upper-login-window">
		
		<form autocomplete="off" name="loginForm" id="loginForm" action="" method="POST">
		
		<label for="name" id="login-username">Username:</label>
		
		<input type="name" name="username" id="username-login" onclick="this.value=''" />
		
		<label for="username" id="login-password">Password:</label>
		
		<p><a id="forgetPassword" href="#">Forgot your password?</a>
		
		<input type="password" name="password" id="password-login" onclick="this.value=''" />

                <img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="securimage/securimage_show.php?sid=779b77d5c67e072a69587a319ca5e1be" alt="CAPTCHA Image" align="center" onclick="this.blur()" />

                <object type="application/x-shockwave-flash" data="securimage/securimage_play.swf?bgcol=#ffffff&amp;icon_file=securimage/images/audio_icon.png&amp;audio_file=securimage/securimage_play.php" width="20" height="20">
                <param name="movie" value="securimage/securimage_play.swf?bgcol=#ffffff&amp;icon_file=securimage/images/audio_icon.png&amp;audio_file=securimage/securimage_play.php" />
                </object>


                <a id="refresh-captcha" href="#" title="Refresh Image" onclick="document.getElementById('siimage').src = 'securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false"> 
	 
                <img src="images/refresh.png" alt="Reload Image" height="20" width="20" onclick="this.blur()" align="bottom" border="0" />
  
                </a>

		<input type="captcha" name="captcha_code" id="captcha_code" onclick="this.value=''" placeholder="Enter Code" />
	
		<div id="lower-login-window">
		
		<input type="checkbox" name="keepMe" id="keepMe" value="false" ><label class="check" for="checkbox" id="login-keepMe">Keep me logged in</label>
		
		<input type="submit" id="button-login" value="Login">
		
		</div>
		
		</form>
		
	</div>
	
	<!-- End Page Content -->
<script src="js/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
    $.noConflict();

    function reloadCaptcha()
    {
        jQuery('#siimage').src = 'securimage/securimage_show.php?sid=' + Math.random();
    }
      $(function () {
        $('#loginForm').on('submit', function (e) {
          $.ajax({
            type: 'post',
            url: 'check_login.php',
            data: $('#loginForm').serialize(),
            success: function (response) {
               if(response=="true"){
                   $("#main").load("content.php");
                   $("#menu").load("menu.php");
                   $("#header").load("header.php");
               } else {
                   alert(response);
                   $("#main").load("login.php");
               }
            }
          });
          e.preventDefault();
        });
      });
   $("#keepMe").click(function() {
       if($(this).is(":checked")) {
           $(this).val('true');
      }else{
           $(this).val('false');
     }
}); 
</script>
 </div>
 </div>
</BODY>
</HTML>

Open in new window



logout.php
    $response="";
    session_destroy();
    session_unset();
    $_SESSION = array();
    $_SESSION = array_filter($_SESSION);
    if( !isset($_SESSION['username']) ) {
       $response="true";
    }
    else {
       $response="true";
     }
    echo $response;

Open in new window


check_session.php
<?php
session_start();
$status="";
if( empty($_SESSION['username']) ) {
     $status="false";
}
else {
     $status="true";
}
echo $status;
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Marco Gasi
    if( !isset($_SESSION['username']) ) {
       $response="true";
    }
    else {
       $response="true";
     }

Open in new window


This piece of code always returns true.
See also this function: array_filter() does not make sense with only one argument.  I would remove that.
Avatar of Ashraf Hassanein
Ashraf Hassanein

ASKER

Always too fast in answering back, yes indeed I forgot to add session start in the begining however it is not clear to me how to state session_startat the start of the file killing the session, but I have to live with the facts :-)
Well my usual comment, Ray is great in supporting people
Thank you marqusG that was helpful.
I love 2014 I have 2 experts supporting me Yessss
Thanks for using Experts-Exchange and Happy New Year 2014! ~Ray
Happy new year Ray,
Happy new year marqusG
Happy New Year to you from me too :)
Hi Ray, I understood that the interpretation of this form:
$uid = (isset($_SESSION["uid"])) ? ', ' . $_SESSION["uid"] : ' NOW';

Open in new window


Is
 
if  (isset($_SESSION["uid"]))
{ 
   $uid = $_SESSION["uid"] ;
}

Open in new window


correct?
What you're seeing there is the PHP ternary operator form of the if() statement.   Here is the annotation comparing ternary and conventional if()

// TERNARY OPERATOR
$uid = (isset($_SESSION["uid"])) ? ', ' . $_SESSION["uid"] : ' NOW';


// EXPANDED IF STATEMENT
if (isset($_SESSION["uid"]))
{
    // CREATE A MESSAGE-STRING FRAGMENT THAT SHOWS THE USER'S NAME
    $uid = ', ' . $_SESSION["uid"];
}
// IF WE DO NOT HAVE THE USER'S NAME IN THE SESSION
else
{
    // CREATE A MESSAGE-STRING FRAGMENT THAT MAKES SENSE EVEN WITHOUT THE NAME
    $uid = ' NOW';
}

Open in new window

I find the ternary operator to be useful for simple if() constructs like this -- it saves typing.  I have also found some really screwed up code when programmers try to get complicated with the ternary operator, so I recommend keeping it simple with only two options.  Nothing can be as hard to understand as nested ternary operators (except maybe regular expressions).
Thanks for your help