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
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();
}
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
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