is it possible to set unlimited time for a cookie to a session variable?

拥有回忆 提交于 2019-12-20 02:47:36

问题


How do I set unlimited time to a cookie for a session? I have tried the following below but I still get undefined index notices on my sessions after a day:

setcookie('idcourse', 'CourseID', 9999999999);
setcookie('namecourse', 'CourseName', 9999999999);
setcookie('id', 'ID', 9999999999);

if (isset($_POST['idcourse'])) {

$_SESSION['idcourse'] = $_POST['idcourse'];

}

if (isset($_POST['namecourse'])) {

$_SESSION['namecourse'] = $_POST['namecourse'];

}

if (isset($_POST['id'])) {

$_SESSION['id'] = $_POST['id'];

}

回答1:


You must add an expiry date, or the cookie will act like a session and expire when you leave the website,

what you're doing is nearly right but you need to change it slightly;

You are setting expire 9999999999 (you need to specify a UNIX TIMESTAMP in the future), so i use the following:

$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('idcourse', 'CourseID', $inTwoMonths );
setcookie('namecourse', 'CourseName', $inTwoMonths );
setcookie('id', 'ID', $inTwoMonths );

will make the cookie expire in 2 months, you can increment this accordingly.




回答2:


You should not set cookies to unlimited time. If you need to store something for a longer period, use localStorage. They don't expire. They're not really cookies but it's also a way of setting information in the browser. You just have to use JavaScript with this.

As for PHP, what you can do is you can rely on databases that will store your information permanently. You can set things in local storage that you can use to load session information. But my suggestion is just use localStorage.



来源:https://stackoverflow.com/questions/12355931/is-it-possible-to-set-unlimited-time-for-a-cookie-to-a-session-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!