that is because the PHP (that is, the session_destroy() function) is executed before the complete HTML is sent to the browser and JavaScript can be executed. (also note the output of your PHP code in the HTML source code – there shouldn’t be any)
to solve this there are several possibilities
1) make an AJAX call to a PHP script file, that executes session_destroy()
- // JavaScript, pseudo code
-
function logout()
-
{
-
// simply calling the logout.php page
-
Ajax.post("logout.php");
-
}
-
// PHP
-
<?php # file: logout.php
-
session_start();
-
session_destroy();
-
?>
2) submit a form (you only need the submit button) to this page and if the button was pressed, destroy the session.
- // HTML/PHP
-
<form action="" method="post">
-
<input type="submit" name="logout" value="yes">
-
<?php
-
if (isset($_POST["logout"]))
-
{
-
session_destroy();
-
}
-
?>
-
</form>
3) reload the page via JavaScript, passing an URL parameter indicating the session to be killed.
- // JavaScript
-
function logout()
-
{
-
window.location.href = "page.php?logout=yes";
-
<?php
-
if (isset($_GET["logout"]))
-
{
-
session_destroy();
-
}
-
?>
-
}