对于会话变量的未定义索引,即使我已经设置了cookie
问题描述:
I am trying to set cookies to a php session variable so that a session does not expire for 2 months. The problem I am getting though is that after about 3 hours, when I refresh the page, I get a undefined index for $_SESSION['id']
in line 30. But I don't get the undefined index for $_SESSION['id']
in between lines 20-23.
Why am I still getting undefined indexes even though I have set cookies for this session variable?
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('id', 'ID', $inTwoMonths);
//line 20-23
if (isset($_POST['id'])) {
$_SESSION['id'] = $_POST['id'];
}
//line 30
<?php echo $_SESSION['id'] ?>
答
SESSION != COOKIE.
You must set SESSION TTL in php.ini (20min default).
On line 20-23 you dont get undefined index, coz you setting var. But on line 30 you trying to read undefined variable(coz you dont set-up it before.)
Try something like this:
$_SESSION['id'] = $_COOKIE['id'];
Also you need use session_start(); to init session.