Hello PHP team!
The following code:
<?php
class Foo {
}
setcookie('name', 'value', array(
'expires' => 1,
'path' => new Foo()
));
?>
throws an error message that goes like this:
PHP Fatal error: Uncaught Error: Object of class Foo could not be
converted to string in ...
Stack trace:
#0 ...: setcookie()
#1 {main}
thrown in ...
so I would expect no `Set-Cookie` header to be send because of this
fatal error. However, after wrapping this code in a try/catch block, I
noticed it actually sent the header:
Set-Cookie: name=value; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
It looks like the `Error` exception is thrown somewhere after sending
the cookie header. Why does it work in this way? Is it ok?
The call above is almost a synonym for this invocation:
setcookie('name', 'value', 1, => new Foo());
Except that it does not send the cookie header.
I tested it with PHP 8.0.3 on an ArchLinux box; what follows is a test file:
--TEST--
setcookie() sends header before throwing `Error` exception
--FILE--
<?php
ob_start();
class Foo{
}
try {
setcookie('name', 'value', array(
'path' => new Foo()
));
} catch (\Error $e) {
echo $e->getMessage() . "\n";
}
var_dump(headers_list());
echo "Done\n";
?>
--EXPECTHEADERS--
--EXPECTF--
Object of class Foo could not be converted to string
array(1) {
[0]=>
string(23) "X-Powered-By: PHP/8.0.3"
}
Done
Thank you very much for your help,
Regards,
Jair López