Reputation: 1816
In our intranet, each user can log in and cookies are created when the user is sucessfully connected
setcookie('id_user', $res['id_user'], time()+600, '/');
setcookie('email', $res['mail'], time()+600, '/');
setcookie('firstname', $res['firstname'], time()+600, '/');
setcookie('lastname', $res['name'], time()+600, '/');
They will expire after 10 min.
I have many pages where js function are using the $_COOKIE
variables.
I do not want to check if $_COOKIE
is null or not for every function.
Is there a way to trigger a js function to check if the cookie is still available ?
I tried this
var user = '<?php echo $_COOKIE['id_user']; ?>';
function check()
{
if(user === null)
{
console.log('logged');
}
else
{
console.log('disconnected');
}
}
check();
setInterval(check, 1000);
But it did not worked. When I'm connected before accessing to this page. The console is always showing 'connected' even when I disconnect from another page. I think the cookie is still present in the page and did not expire.
And if I am not connected before accessing the page, an js error tell me
SyntaxError: unterminated string literal
var user = '<br />
Upvotes: 2
Views: 6684
Reputation: 1816
I managed this using the following js. This code will check every sec if the cookie is still available.
function check()
{
var user = getCookie('firstname');
if(user == '')
{
console.log('disconnected');
}
else
{
console.log('connected');
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
check();
setInterval(check, 1000);
Upvotes: 2