问题描述
在我们的内联网中,每个用户都可以登录并在用户成功连接时创建cookie
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, '/');
他们将在10分钟后过期。
They will expire after 10 min.
我有很多页面,其中js函数使用 $ _ COOKIE
变量。
我不想检查每个函数 $ _ COOKIE
是否为空。
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.
是有没有办法触发js函数检查cookie是否仍然可用?
Is there a way to trigger a js function to check if the cookie is still available ?
我试过这个
var user = '<?php echo $_COOKIE['id_user']; ?>';
function check()
{
if(user === null)
{
console.log('logged');
}
else
{
console.log('disconnected');
}
}
check();
setInterval(check, 1000);
但它没有用。在访问此页面之前我已连接。即使我断开与其他页面的连接,控制台也始终显示已连接。我认为cookie仍然存在于页面中并且没有过期。
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.
如果我在访问页面之前没有连接,则js错误告诉我
And if I am not connected before accessing the page, an js error tell me
SyntaxError: unterminated string literal
var user = '<br />
推荐答案
我使用以下js管理了这个。如果cookie仍然可用,此代码将每秒检查一次。
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);
这篇关于检查cookie是否仍然有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!