foreach之后没有保存PHP Cookie

时间:2017-01-25 11:43:59

标签: php cookies

我无法在foreach之后保存cookie。在foreach之前,cookie被完美保存。

例如,这很好用:

<?php
setcookie('test', 'This is a test', time() + 3600 , '/', '.mydomain.com');    

if(isset($_COOKIE['test'])){
   echo 'The cookie is ' . $_COOKIE['test'];
} else {
   echo 'No cookie has been set';
}

foreach ($values as $value){  
  // CODE
  echo $value;
}
?>

但是使用此代码,我无法保存Cookie:

<?php
foreach ($values as $value){  
  // CODE
  echo $value;
}

setcookie('test', 'This is a test', time() + 3600 , '/', '.mydomain.com');    

if(isset($_COOKIE['test'])){
   echo 'The cookie is ' . $_COOKIE['test'];
} else {
   echo 'No cookie has been set';
}
?>

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

Cookie只能在输出之前设置...因此,如果您在foreach循环中输出,则之后无法设置Cookie。

但是,我相信你实际上可以使用输出缓冲来解决这个问题...所以以下应该可以正常工作......

ob_start();
setcookie(...);
ob_end_flush();

答案 1 :(得分:0)

最后用这段代码解决了:

<?php
ob_start();
foreach ($values as $value){  
  // CODE
  echo $value;
}

setcookie('test', 'This is a test', time() + 3600 , '/', '.mydomain.com'); 
ob_end_flush();    

if(isset($_COOKIE['test'])){
   echo 'The cookie is ' . $_COOKIE['test'];
} else {
   echo 'No cookie has been set';
}
?>