Search code examples
phpsessionauthenticationreloadlogout

How to automatically refresh a page and redirects to login page when session has expired (PHP)


Please excuse me, I know there are some questions on stack overflow regarding this, but I don't find any solution that suits my problem. I've a problem, when the session is expired the page is not reloading automatically. Please help. Thank You! Any help would be appreciated.

This is the code I've tried, $_SESSION['created'] = time();

if((time() - $_SESSION['created']) > 600) {
    header("Refresh: 1;url='logout.php'");
} else {
    $_SESSION['created'] = time();
}

Solution

  • As per your need you have to check the session each seconds once session is valid or not in server side so do something like this.

    1) Created a javascript and ajax for checking a session is expired or not in server side each seconds once

    2) session.php page to check the valid session or not

    3) Then return the 1 or -1 based on that trigger the location.reload() function it automatically moved to logout.php because your top condition become true now.

    session.php

            <?php
    
                session_start();
    
    
                if(!isset( $_SESSION['created'] ) || (time() - $_SESSION['created']) > 600) {
    
                    session_destroy();
    
                    echo "-1";
    
                } else {
    
                    echo "1";
    
                }
    
            ?>
    

    Paste this javascript in each and every page

    Java Script :

            <script type="text/javascript">
    
                    function session_checking()
                    {
                        $.post( "session.php", function( data ) {
    
                            if(data == "-1")
                            {
                                alert("Your session has been expired!");
                                location.reload();
                            }
    
                        });
                    }
    
                    var validateSession = setInterval(session_checking, 1000);
    
        </script>
    

    This code should be each page top

    if(!isset( $_SESSION['created'] ) || (time() - $_SESSION['created']) > 600)   {
    header("Refresh: 1;url=logout.php");
    } else {
    $_SESSION['created'] = time();
    }