0

I can not save a cookie after a foreach. Before the foreach the cookie is saved perfectly.

For example, this works fine:

<?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;
}
?>

But with this code, I can't save the 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';
}
?>

Any ideas?

kurtko
  • 1,978
  • 4
  • 30
  • 47

2 Answers2

0

Cookies can only be set BEFORE OUTPUT... therefore if you are outputting in your foreach loop, cookies can not be set afterwards.

However, I believe you can actually use output buffers to work around this problem... So the following should work just fine...

ob_start();
setcookie(...);
ob_end_flush();
Reel
  • 354
  • 2
  • 4
  • 14
0

Finally solved with this code:

<?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';
}
?>
kurtko
  • 1,978
  • 4
  • 30
  • 47
  • Great! I can advise to structure your code in a way that you won't need that next time though, It's (almost) always possible through proper structure. – Nytrix Jan 25 '17 at 12:03