9

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?

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

i found a solution, it has to have 3 digits

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

similarly in header function

header('HTTP/1.0 024');

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.