Solved

Php session can not be terminated

Posted on 2014-01-01
12
542 Views
Last Modified: 2014-01-01
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

0
Comment
Question by:Ashraf Hassanein
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 2
12 Comments
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39749758
This article shows how to handle PHP client authentication, including Login and Logout.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

Here is the "minimalist" logout script.  Note the use of session_start()!
<?php // RAY_EE_logout.php
error_reporting(E_ALL);
session_start();

// CLEAR THE INFORMATION FROM THE $_SESSION ARRAY
$_SESSION = array();

// IF THE SESSION IS KEPT IN COOKIE, FORCE SESSION COOKIE TO EXPIRE
$cookie_expires = time() - 86400;
if (isset($_COOKIE[session_name()]))
{
    setcookie(session_name(), '', $cookie_expires, '/');
}

// TELL PHP TO ELIMINATE THE SESSION
session_destroy();

// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;

Open in new window

0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39749762
    if( !isset($_SESSION['username']) ) {
       $response="true";
    }
    else {
       $response="true";
     }

Open in new window


This piece of code always returns true.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39749764
See also this function: array_filter() does not make sense with only one argument.  I would remove that.
0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 

Author Comment

by:Ashraf Hassanein
ID: 39749773
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 :-)
0
 

Author Closing Comment

by:Ashraf Hassanein
ID: 39749787
Well my usual comment, Ray is great in supporting people
0
 

Author Comment

by:Ashraf Hassanein
ID: 39749791
Thank you marqusG that was helpful.
I love 2014 I have 2 experts supporting me Yessss
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39749798
Thanks for using Experts-Exchange and Happy New Year 2014! ~Ray
0
 

Author Comment

by:Ashraf Hassanein
ID: 39749801
Happy new year Ray,
Happy new year marqusG
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39749812
Happy New Year to you from me too :)
0
 

Author Comment

by:Ashraf Hassanein
ID: 39749813
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?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39749818
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).
0
 

Author Comment

by:Ashraf Hassanein
ID: 39749824
Thanks for your help
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question