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';
}
}
});
});
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With