A free and open-source book on ZF3 for beginners

4.6. Putting Data to HTTP Response

Although you rarely interact with HTTP response data directly, you can do that with the help of getResponse() method provided by the AbstractActionController base class. The getResponse() method returns the instance of Zend\Http\PhpEnvironment\Response class. Table 4.4 contains the most important methods of this class:

Table 4.4. Methods of Zend\Http\PhpEnvironment\Response class.
Method Name Description
fromString($string) Populate response object from string.
toString() Renders entire response as HTTP response string.
setStatusCode($code) Sets HTTP status code and (optionally) message.
getStatusCode() Retrieves HTTP status code.
setReasonPhrase($reasonPhrase) Sets the HTTP status message.
getReasonPhrase() Gets HTTP status message.
isForbidden() Checks if the response code is 403 Forbidden.
isNotFound() Checks if the status code indicates the resource is not found (404 status code).
isOk() Checks whether the response is successful.
isServerError() Checks if the response is 5xx status code.
isRedirect() Checks whether the response is 303 Redirect.
isSuccess() Checks whether the response is 200 Successful.
setHeaders(Headers $headers) Allows to set response headers.
getHeaders() Returns the list of response headers.
getCookie() Retrieves Cookie header.
setContent($value) Sets raw response content.
getContent() Returns raw response content.
getBody() Gets and decodes the content of the response.

For example, use the following code to set 404 status code for the response:


Use the following code to add a header to response:

$headers = $this->getResponse()->getHeaders();
             "Content-type: application/octet-stream");

Use the following code to set response content:

$this->getResponse()->setContent('Some content');