• Howdy! Welcome to our community of more than 130.000 members devoted to web hosting. This is a great place to get special offers from web hosts and post your own requests or ads. To start posting sign up here. Cheers! /Peo, FreeWebSpace.net
managed wordpress hosting

Can not set cookies in PHP

hostingreviews

New Member
For some I can not set cookies in PHP on one my sites. The error that displays on my web page is:

"Warning: Cannot modify header information - headers already sent by(...)"

This happens when I try to set a cookie, for example, when I use this code:

HTML:
<html>
<head><title>cookie</title></head>
<body>

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


 if(isset($_COOKIE['test'])){
  echo 'The cookie is ' . $_COOKIE['test'];
 }

?>

</body>
</html>

Can someone tell me what I'm doing wrong?

Thanks
 
Info for other people: before any other output,
<?php ob_start(); ?>

ie

Code:
<?php ob_start(); ?><html>
<head><title>cookie</title></head>
<body>

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


 if(isset($_COOKIE['test'])){
  echo 'The cookie is ' . $_COOKIE['test'];
 }

?>

</body>
</html>
 
Info for other people: before any other output,
<?php ob_start(); ?>

you dont need ob_start Colin. cookies have to be set and checked before heading info is sent.

PHP:
<?php
  setcookie('test', 'This is a test', time() + 3600);

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

?>

<html>
<head><title>cookie</title></head>
<body>

<?=$cookieSet?>

</body>
</html>
 
Back
Top