Is it possible to run session_destroy();
on a button click?
I understand the usual use would be to create a page dedicated to it for example logout.php
and link the button to that, but for simplicity is it not just possible to run it on a button click?
Not directly. session_destroy();
runs on the Server, your Button on the Client.
What you can do, is an Ajax call to logout.php
on Button Click.
Client:
<script>
$('#LogoutButton').click(function() {
var request = $.ajax({
url: "/path/to/logout.php",
type: "GET"
});
request.done(function(msg) {
alert("Logged Out");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Logging Out");
});
});
</script>
<button id="LogoutButton">Logout</button>
Logout.php
<?php
session_destroy();
?>
Regards
Instead of the AJAX answer, you could wrap the button in a <form>
element, then have the form post to the same page. For example
<form action="" method="post">
<input type="hidden" name="logout" value="true" />
<button>Logout</button>
</form>
Then in your PHP at the head of the document:
if(isset($_POST['logout'])) {
unset($_SESSION[/*your user variables here*/ ]);
session_destroy();
}
This would have to be at the head of every page, and is a little less neat than the AJAX answer because of that, but would do away with the need for a logout.php
file