cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

\Phalcon\Mvc\Micro setting response headers

Open nesbert opened this issue 14 years ago • 2 comments

The service I am writing needs to be able to set HTTP Status Codes depending on the request result. I was wonder how come I am unable to change headers using the code below:

<?php
$app = new Phalcon\Mvc\Micro();
$app->getSharedService('response')->setContentType('application/json', 'utf-8');

$app->notFound(function() use ($app) {
    $app->response->setStatusCode(404, null);
    echo json_encode(array('error' => 'Not Found'));
});

$app->post('/user/auth', function() use ($app){
    try {
        throw new \Exception('Authentication Failed', 401);
    } catch (\Exception $e) {
        $app->response->setStatusCode($e->getCode(), null);
        echo json_encode(array('error' => $e->getMessage()));
    }
});

$app->handle();

HTTP/1.1 200 OK Content-Length: 21 Date: Sat, 15 Sep 2012 04:50:25 GMT Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.16 mod_ssl/2.2.22 OpenSSL/0.9.8r X-Powered-By: PHP/5.3.16 Connection: close Content-Type: text/html; charset=UTF-8

{"error":"Not Found"}


HTTP/1.1 200 OK Content-Length: 33 Date: Sat, 15 Sep 2012 04:50:33 GMT Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.16 mod_ssl/2.2.22 OpenSSL/0.9.8r X-Powered-By: PHP/5.3.16 Connection: close Content-Type: text/html; charset=UTF-8

{"error":"Authentication Failed"}

nesbert avatar Sep 15 '12 04:09 nesbert

Hi Nesbert, setStatusCode adds a header to the headers bag, and it's necessary send it then:

https://github.com/phalcon/mvc/blob/master/micro/index.php#L23

ghost avatar Sep 15 '12 05:09 ghost

Hi, sorry I missed that missed that! For some reason I thought the response object being modified in the closure would automatically be used. :)

Thanks for the quick response!

nesbert avatar Sep 15 '12 05:09 nesbert