-1

I'm totally new to php (just started learning recently) and I'm facing an issue with cookies

here's the error/warning I'm getting:

Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/cookies.php:5) in /Applications/XAMPP/xamppfiles/htdocs/cookies.php on line 5

all what I've written inside the file is this:

<body>
<?php 
setcookie('test', 45, time()+(60*60*24*7));
?>
</body>

** I'm using XAMP on Mac

Any idea why this is happening and how can I fix/deal with it ?

thanks,

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
MCH
  • 986
  • 13
  • 19

3 Answers3

0

yes, because <body> is before setcookie. Setcookie needs to come first

<?php 
setcookie('test', 45, time()+(60*60*24*7));
?>
<body>
</body>

From http://php.net/setcookie:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Kris
  • 6,094
  • 2
  • 31
  • 46
0

Use it without any space. you need to declare them at the very top of your code..same thing happens with header("location:xyz.php"). So keep that in your mind for future use.

<?php 
    setcookie('test', 45, time()+(60*60*24*7));
    ?>
<body>
//Your code here
</body>
Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23
0

Headers must sent before any output. And cookies will send in headers.

Ahmet Mehmet
  • 288
  • 2
  • 10