How to session timeout warning with countdown using PHP, Ajax and HTML

In this tutorial we will show you how to display session timeout warning with countdown using PHP, Ajax and HTML.When user logged in using login form we display a countdown and after the countdown end user will be logged out automatically.

HTML and jQuer Code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            function start_countdown()
            {
                var counter = 10;
                myVar = setInterval(function ()
                {
                    if (counter >= 0)
                    {
                        document.getElementById("countdown").innerHTML = "You Will Be Logged Out In <br>" + counter + " Sec";
                    }
                    if (counter == 0)
                    {
                        $.ajax
                        ({
                            type: 'post',
                            url: 'logout.php',
                            data: {
                                logout: "logout"
                            },
                            success: function (response)
                            {
                                location.reload();
                            }
                        });
                    }
                    counter--;
                }, 1000)
            }
        </script>
    </head>
    <body>
        <?php
        if (@$_SESSION['password'] == "123456" && @$_SESSION['name'] == "123456") {
            ?>
            <script>start_countdown();</script>
            <p id="countdown"></p>
            <?php
        }
        ?>
    </body>
</html>

PHP Code (logout.php)

<?php
if(isset($_POST['logout']))
{
 unset($_SESSION['name']);
 unset($_SESSION['password']);
 echo "success";
 exit();
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *