Destroy PHP SESSION in Javascript Function
26,716
Solution 1
I think you should use AJAX to destroy function from Javascript. Like :
.js
code :
function destroy_session(){
var xmlhttp = getXmlHttp();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','./destroy_session.php', true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
destroy_session.php
code:
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
echo 'Session was destroyed';
?>
Solution 2
you cant directly destroy the session of php within javascript, since javascript is running on the client and php is running on the server.
but you can erase the session cookie from php within php - when its used!
but this detaches only the client from the session, no destroying the session.
Author by
Tomas
Updated on July 09, 2022Comments
-
Tomas almost 2 years
I create a
session
in myphp
script.
I want to destroy myphp session
in javascript.
when I click onDestroy Session
then javascript functiondestroy()
call and destroySESSION['user']
.<?php ob_start(); session_start(); SESSION['user'] = "test 123"; echo "<a onClick = 'destroy()'>Destroy Session</a>"; ?> <script> Function destroy(){ session_destroy(); // Like `PHP` I want destroy Session in `javascript` } </script>