is it possible to set unlimited time for a cookie

2019-02-26 04:32发布

问题:

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.