Using CakePHP 3.4, PHP 7.0.
I'm attempting to do a really simple controller method to output some JSON. It is outputting "Cannot modify headers...".
public function test() {
$this->autoRender = false;
echo json_encode(['method' => __METHOD__, 'class' => get_called_class()]);
}
Browser output
{"method":"App\Controller\SomeController::test", "class":"App\Controller\SomeController"}
Warning (512): Unable to emit headers. Headers sent in file=...
Warning (2): Cannot modify header information - headers already sent by (output started at ...)
Warning (2): Cannot modify header information - headers already sent by (output started at ...)
I fully understand why PHP complains about this. The question is why does CakePHP complain and what can I do about it?
It should be noted that CakePHP 2.x allowed this.
Controllers should never echo data! Echoing data can lead to all kinds of problems, from the data not being recognized in the test environment, to headers not being able to be sent, and even data being cut off.
Doing it that way was already wrong in CakePHP 2.x, even though it might have worked in some, maybe even most situations. With the introduction of the new HTTP stack, CakePHP now explicitly checks for sent headers before echoing the response, and will trigger an error accordingly.
The proper way to send custom output was to configure and return the response object, or to use serialized views, and it's still the same in 3.x.
Quote from the docs:
* As of 3.4 that would be
CakeHttpResponse
Cookbook > Controllers > Controller Actions
Configure the response
Using the PSR-7 compliant interface
The PSR-7 compliant interface uses immutable methods, hence the utilization of the return value of
withStringBody()
andwithType()
. In CakePHP < 3.4.3,withStringBody()
is not available, and you can instead directly write to the body stream, which will not change the state of the response object:Using the deprecated interface
Use a serialized view
This requires to also use the request handler component, and to enable extensing parsing and using correponsing URLs with
.json
appended, or to send a proper request with aapplication/json
accept header.See also