<?php
if (!isset($_COOKIE['visits']))
{
$_COOKIE['visits'] = 0;
}
$visits = $_COOKIE['visits'] + 1;
setcookie('visits', $visits, time() + 3600 * 24 * 365);
include 'welcome.html.php';
welcome.html.php:
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cookie counter</title>
</head>
<body>
<p>
<?php
if ($visits > 1)
{
echo "This is visit number $visits.";
}
else
{
// First visit
echo 'Welcome to my website! Click here for a tour!';
}
?>
</p>
</body>
</html>
When I run this in browser (chrome or opera) it can’t work - the message that appears is:
Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\xampp\xampp\htdocs\cookie2\index.php:1) in C:\Program Files\xampp\xampp\htdocs\cookie2\index.php on line 7
Can someone help me to solve this error?
Have you got any spaces, blank lines or anything before the opening <$php in your index.php file? If you have, remove it. Any blanks before the opening PHP will be sent to the browser for output, which will also send the headers, and once they’re sent, you can’t send them again (which setcookie() is doing).
It’s this part of the error message that makes me wonder if the problem is white-space before the opening php bracket:
To me that implies that output started at line 1 of the code, so line 7 (which is probably the setcookie() function) can’t run. I must admit I can’t remember if error line numbers are base zero or one.
I don’t know what was the reason of the error:
output started at C:\Program Files\xampp\xampp\htdocs\cookie2\index.php:1 -
I opened my code in different editors but nothing I could see before the opening PHP… I resaved this file in aptana studio and now it’s ok.)