Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
106 lines (74 sloc) 2.15 KB


HTTP response contains status code and message, a set of headers and a body:

HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 6 
Content-Type: text/html
Connection: Closed


Yii uses PSR-7 Response in the web applicaiton in order to represent response.

The object should be constructed and returned as a result of execution of controller actions or other type of middleware. Usually the middleware has response factory injected into its constructor.

class PostAction
    private $responseFactory;

    public function __construct(ResponseFactoryInterface $responseFactory)
        $this->responseFactory = $responseFactory;

public function view(ServerRequestInterface $request): ResponseInterface
    $response = $this->responseFactory->createResponse();
    return $response;

Status code

Setting status code is done like the following:

$response = $response->withStatus(404);


Headers could be set like this:

$response = $response->withHeader('Content-type', 'application/json');

In case there is a need to append a header value to existing header:

$response = $response->withAddedHeader('Set-Cookie', 'qwerty=219ffwef9w0f;; Path=/; Expires=Wed, 30 Aug 2019 00:00:00 GMT');

And, if needed, headers could be removed:

$response = $response->withoutHeader('Set-Cookie');


Response body is an object implementing Psr\Http\Message\StreamInterface.

Writing to it could be done via the interface itself:

$body = $response->getBody();



return $response
  ->withHeader('Location', '');  

Responding with JSON

$data = [
    'account' => 'samdark',
    'value' => 42

return $response
          ->withHeader('Content-Type', 'application/json');
You can’t perform that action at this time.