ad

How to Check If User Has Logged Out From Other Tab

session check

In Facebook if you are using multiple tabs and logout from any of the tabs, other tab show a popup alert, “you have logged out. Please login again.” What if you want to implement this kind of thing. One of my readers asked me to write an article on this.

Session Check AJax php

To implement this, you can use ajax calls and implement setInterval() method of js to keep checking the session.

First create a php file which returns the status of the session.

sessioncheck.php

<?php
session_start();

if(isset($_SESSION['id']))
{
echo('1'); 
}
else
{
echo('0');
}
?>

Now create a jQuery function to create ajax call and popup a message if user has logged out.

<script type="text/javascript">
var check_session;
function CheckSession() {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "sessioncheck.php",
data: str,
cache: false,
success: function(responce){
if(responce == "0") {
alert('Your have already been logged out!');
window.location.replace("index.php");
}
}
});
}
</script>

Now call this JavaScript function in every 5 or 10 seconds to keep checking sessions. I am using 5 seconds time interval

<script>
check_session = setInterval(CheckSession, 5000);
</script>

 Demo

Tags: |
Nord VPN Sale

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip Developed By Deepanker