Search code examples
phpsetcookie

setcookie() always fails "headers already sent" even following the rules on php.net


The relevant peice of code is below. According to php.net I have to make sure there is no output, not even any whitespace. There isn't any. the php tag is the very first tag in the document no whitespace preceding it. What am I doing wrong?

<?php

    // main.php
    // 6:48 PM 8/6/2010

    include('config.php');

    // Does myid cookie exist?
    if ( !isset( $_COOKIE['myid'] ) )
    {
        // Generate myid
        $myid = substr(md5(date( 'Ymdhis' ) . str_replace( '.', '', $_SERVER['REMOTE_ADDR'] ) ), 0, 10);

        // set the cookie
        setcookie( 'myid', $myid, time() + 31536000 );

Solution

  • There needs to be no output at all before calling setcookie, even from other scripts.

    If config.php had whitespace before the opening <?php tag (or after the closing ?>), for example, that would cause the problem.

    Hunt down where header is called or some text outside of PHP tags (even whitespace) exists. That's what's happening, no doubt.