Cookies are not work normal

From this book: http://www.sitepoint.com/store/php-mysql-novice-to-ninja/ I download a code - cookiecounter - chapter9:

index.php:

<?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).

No, <?php is the beginning of code… I checked it in Aptana studio.

unless you have a byte order mark in front of it - that doesn’t show in all editors.

how I can see it? In what editor, for example?

What is on line 7? as that is in your error message

C:\Program Files\xampp\xampp\htdocs\cookie2\index.php on line 7

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.)

Did you check the editors encoding settings?
The files encoding?

What you describe is a classic example of BOM trouble

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.