Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 966
Piotr M Avatar asked Dec 09 '10 13:12

Piotr M


3 Answers

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

like image 182
Julian Reschke Avatar answered Sep 30 '22 20:09

Julian Reschke


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
like image 20
HPierce Avatar answered Sep 30 '22 19:09

HPierce


i found a solution, it has to have 3 digits

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

similarly in header function

header('HTTP/1.0 024');
like image 44
Piotr M Avatar answered Sep 30 '22 19:09

Piotr M