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

18,891

Solution 1

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

Solution 2

I see this question is tagged with , 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

Solution 3

i found a solution, it has to have 3 digits

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

similarly in header function

header('HTTP/1.0 024');
Share:
18,891
Piotr M
Author by

Piotr M

Updated on June 04, 2022

Comments

  • Piotr M
    Piotr M almost 2 years

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

    i need to return status 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?