0

The following code will only be called when a session has timed out. I basically want to display a confirm dialog with javascript to make the user pick if he wants to remain online or not. My problem is that the php that closes the session inside the javascript seems to be executed even if the confirm is true.

if (isset($_SESSION['username']) && isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 5)) {
    ?>
    <script type="text/javascript">
    if (confirm("You were logged off due to inactivity, if you would like to remain logged in click OK.")) {
        header("Location:/");
    } else {
    <?php
    connect();
    if(!connect()) {
        die('Could not connect: ' . mysql_error());
        header( "refresh:3; url=/index.php" );
    }
    mysql_select_db('www');
    $user = $_SESSION['username'];
    mysql_query("UPDATE users SET online='0'
    WHERE username='$user'");
    session_unset();
    session_destroy();
    ?>
    }
    </script>
<?php
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>
1
  • Move your php code in else part to a PHP file and send either an ajax call to it or redirect to it via window.location. The problem is mentioned by @rightfold Commented Dec 29, 2013 at 9:19

1 Answer 1

2

The PHP code is run before the page is loaded by the browser. JavaScript is run after the page is loaded by the browser. You cannot just mix them like this and expect everything to somehow happily work. See HTTP, AJAX and WebSockets.

Sign up to request clarification or add additional context in comments.

1 Comment

The wiki answers didn't help budd :\ Thank you though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.