tags:

views:

72

answers:

1

Hi,

PHPUnit:: How can function that set and get cookies, tested without get error : headers already sent by?

Example that give error:

PHPUnit_Framework_Error_Warning: Cannot modify header information - headers already sent by

MyCookie.php

class MyCookie{
public static function createCookie(){
        $uid = null;
        $cookieName='test_cookie';
        if(!isset($_COOKIE[$cookieName])){
            $uid = unique_hash();
            setcookie($cookieName, $uid, 0, '', '', false, true);
        }
        else{
            $uid=$_COOKIE[$cookieName];
        }
        return $uid;
    }
}

MyCookieTest.php

class MyCookieTest extends PHPUnit_Framework_TestCase{
    public function test_createCookie(){
            MyCookie::createCookie();
            assertThat(isset($_COOKIE['test_cookie']), is(true));
            unset($_COOKIE['test_cookie']);
            MyCookie::createCookie();
            assertThat(isset($_COOKIE['test_cookie']), is(true));
    }
}

Thanks

+1  A: 

If your PHP script does any output, the headers will be sent - And you cannot set cookies anymore. You have to send cookies first before you can output any HTML (or other output).

If you're not outputting any HTML, then it's probably a whitespace somewhere accidentally being output, or the Unicode Byte-Order Mark. If your editor supports it, set it not to include the BOM in UTF-8 encoded files.

Finally, you may use the output buffering functions to delay the sending of any output until you've sent all your headers and set your cookies. (this will not fix accidental output before you begin buffering, though)

Core Xii
I know the problem, but not how to solve that(Your solutions will not work). If you have solution please write it.
Yosef
"My solutions will not work" is not enough. _Why not?_ Why don't they work? What goes wrong? They sure work for me fine.
Core Xii