How to clear a PHP session using Jquery/Javascript?

49,177

Solution 1

Simply put: You can't, directly.

PHP is a server-side language while javascript is a client-side one, which means that there's no other connection between them other than the document you receive and interacts with you. The sessions are stored and managed by the server.

You can, however, as War10ck suggests, call to a server-side script that clears the session. Something like this:

PHP:

<?php
    /* 
     * session_start();
     * Starting a new session before clearing it
     * assures you all $_SESSION vars are cleared 
     * correctly, but it's not strictly necessary.
     */
    session_destroy();
    session_unset();
    header('Location: continue.php'); 
    /* Or whatever document you want to show afterwards */
?>

HTML/javascript:

<script type="text/javascript">
    function logout() {
        document.location = 'logout.php';
    }
    LogoutButton.addEventListener('click', logout, false);
</script>

<button id="LogoutButton">Log out</button>

Or even performing an asynchronous call:

function logout() {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        document.location = 'continue.php';
    }
    xhr.open('GET', 'logout.php', true);
    xhr.send();
}

Solution 2

There is a way you can do it directly from javascript... first you have to declare a function that clears a cookie by its key

function removeCookie(cookieName)
{
    cookieValue = "";
    cookieLifetime = -1;
    var date = new Date();
    date.setTime(date.getTime()+(cookieLifetime*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = cookieName+"="+JSON.stringify(cookieValue)+expires+"; path=/";
}

Now all you have to do is to remove a cookie with the key "PHPSESSID" like this

removeCookie("PHPSESSID");

Now when you var_dump($_SESSION) you find it empty array

Solution 3

You can't clear a php session using Javascript directly.

PHP is a server-side language, whereas Javascript is client-side..

However, you can throw an ajax request to the specified page that handles the destruction.

Like this:

// Client-side
$.post("logout.php", {"can_logout" : true}, function(data){

   if(data.can_logout)
      // redirect the user somewhere
}, "json");


<?php
   // Server-side
   $can_logout = $_POST["can_logout"];

   if($can_logout)
     session_destroy();

   echo json_encode(array("can_logout" => true));
?>

Or just point the user to some page that handles the session destruction; i.e. logout.php

Share:
49,177
Jerielle
Author by

Jerielle

Too many to mention. :-)

Updated on July 24, 2020

Comments

  • Jerielle
    Jerielle almost 4 years

    Just want to ask if is it possible to clear a PHP session using a jquery or javascript process? Because what I want to do is to clear the PHP session using a dialog box. If the user click the 'OK' button it will process the unset function. In my page there's a checkout process and after the user click the button 'OK' it will prompt a dialog box and if the user click the 'OK' button it will unset the PHP session and it will be redirected to another page.

    Here's my simple code:

    <i class="fa fa-check"></i> <span id="save_registry" class="cursor: pointer">OK</span>
    
    <div id="save_alert" style="display: none">
        <?php unset($this->session->data['cart']);
    </div>
    
    
    ....
    
    $('#save_registry').click(function(){
    
            $('#save_alert').dialog({
                modal: true,
                buttons: {
                    Ok: function() {
                        $( this ).dialog( "close" );
                        location = 'index.php?route=common/home'; 
                    }
                }
            });
    
    });
    
  • Jerielle
    Jerielle almost 10 years
    Thanks for the explanation. It really helps me in understanding session. :) I will try your suggestions. Thanks a lot! :)
  • arielnmz
    arielnmz almost 10 years
    Note that javascript is not directly removing the session: the client reads the cookie, invalidates it and sends the proper information to the server, which then expires the session accordingly. +1 for the alternative solution.
  • Adrian Efford
    Adrian Efford over 3 years
    Worked for me ! Thank you