开发者

How to return specific status code (for example 24) in symfony

i need to return crazy http code statuses for API in symfony

i need to return sta开发者_开发百科tus code 24 i try to do it with:

$this->getResponse()->setStatusCode('24');

but i'm always getting response code 500

when i try to return "normal" status code like 404, 403:

$this->getResponse()->setStatusCode('403');

it has no problem

any ideas why?


024 is an invalid HTTP code (this is different from "undefined"). Valid HTTP codes are in the range 100-599.


I see this question is tagged with symfony1, however my answer was tested on Symfony 2.8. A similar solution is likely possible with Symfony 1.X.


When setting a response's status code with $response->setStatusCode(), Symfony preforms a check to confirm that the provided status code is valid according to RFC 2616 - specifically, that it is between 100 - 600:

public function isInvalid()
{
    return $this->statusCode < 100 || $this->statusCode >= 600;
}

As other answers have stated, 24 is out of this range and an exception will be thrown as a result. By using this status code you are not complying with HTTP standards and any normal client might not function as expected. That said, I'm not here to judge your experiment and a solution is available.

You can create a subclass of Response where you override isInvalid() to always return false, thus allowing any and all status codes to be set.

<?php

namespace AppBundle;

use Symfony\Component\HttpFoundation\Response;

class NewResponse extends Response
{
    public function isInvalid()
    {
        //Accept anything.
        return false;
    }
}

Use this class instead of grabbing a standard Response:

/**
 * @Route("/", name="homepage")
 */
public function indexAction(Request $request)
{
    $response = new NewResponse();
    $response->setStatusCode(24);

    return $response;
}

Results in getting the status code you're after:

$ curl -I 127.0.0.1:8000
HTTP/1.1 24 unknown status
Host: 127.0.0.1:8000
Connection: close
X-Powered-By: PHP/5.6.10
Cache-Control: no-cache
Content-Type: text/html; charset=UTF-8
X-Debug-Token: 189e2d
X-Debug-Token-Link: /_profiler/189e2d
Date: Fri, 29 Jan 2016 22:23:29 GMT


i found a solution, it has to have 3 digits

$this->getResponse()->setStatusCode('024');

similarly in header function

header('HTTP/1.0 024');


My guess would be there is no official status code of 24.

Symfony may internally check that.

To get around it, you could do...

header('HTTP/1.0 24');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜