?
Solved

Php session can not be terminated

Posted on 2014-01-01
12
Medium Priority
?
561 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
  • 6
  • 4
  • 2
12 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 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 111

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 111

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 111

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month14 days, 11 hours left to enroll

840 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