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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With