Question

I´m reading that the setcookie() function adds HTTP headers to any page, and thus must be called before any of the actual page content is sent. That makes sense to me.

But after that, there´s this example:

<?php
if (!isset($_COOKIE['visits'])) { $_COOKIE['visits']=0; }
$visits= $_COOKIE['visits'] +1;
setcookie('visits', $visits, time() + 3600);

include 'welcome.inc.php'

...

I mean, if setcookie() mus be first, shouldn´t it be:

setcookie('visits', $visits, time() + 3600);
$visits= $_COOKIE['visits'] +1;

instead of:

$visits= $_COOKIE['visits'] +1;
setcookie('visits', $visits, time() + 3600);

It´s a very newbie question, but can´t quite understand the example in relation to the need of calling setcookie() before everything.

Was it helpful?

Solution

Cookies (like all HTTP Headers) need to be sent before any OUTPUT to the page is made, e.g. before you print() or echo() anything, and you're not allowed to have any text in front of your first <?php.

But

$visits= $_COOKIE['visits'] +1;

doesn't add any output to the page, so it's safe to use it.

OTHER TIPS

http://php.net/setcookie

The doc says that you need to set cookies before your script outputs anything.

Reason:I would have explained it,but this link does a perfect job.Always make sure you invoke setCookie before you echo something.

How to fix "Headers already sent" error in PHP

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top