When I using onclick property to log out of my page and destroy the session its destroy it before I logging out ... here is the code ....
<ul>
<li>
<a href="dispUsers.php">
Display Users
</a>
</li>
<li>
<a href="DispInfo.php">
Display Users Information
</a>
</li>
<li>
<a href="index.php" onclick="<?= session_destroy();?>">
Logout
</a>
</li>
</ul>
what should i do???
Yes! Because your logic is incorrect. PHP does not run on the clients browser like js does. PHP is a server side language.
You could create a new php file called logout.php, also based on what you have provided you don't need the onclick attribute. You can call the logout.php via the href.
The logout.php would contain the logout code and the session_destroy() function.
If you wish to redirect the user to another page after the logout script you can create a redirect header for that, see here.
I'd do it with jQuery and .ajax. Please read the comments on the php block to understand how to effectively kill a php session.
logout.php
<?php
if($_GET['logout'])
{
session_start();
//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), "", time()-3600, "/" );
//clear session from globals
$_SESSION = array();
//clear session from disk
echo session_destroy() ? "Successfully Logged Out" : "An error Occurred";
exit;
}
?>
file.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$( "#logout" ).click(function() {
$.ajax({
type: "GET",
url: 'logout.php',
data: ({ logout : 1 }),
dataType: "html",
success: function(data) {
$( "#output" ).text(data);
$( "#logout" ).hide();
},
error: function() {
$( "#output" ).text(data);
}
});
});
});
</script>
</head>
<body>
<button id="logout"> Logout </button>
<p id="output"></p>
</body>
</html>
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