문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top