Getting the meaning of an HTTP status code with Symfony

Published on 2023-03-06 • Modified on 2023-03-06

This snippet shows how to get the meaning of HTTP response codes with Symfony. It can be done with the help of the Response class and its $statusTexts public property. Did you know that the constants for HTTP status codes were introcuded in Symfony 2.4 in 2013? 🤔


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Response;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet246Trait
{
    public function snippet246(): void
    {
        $errorCode = Response::HTTP_NOT_FOUND;
        $errorConstantName = Response::$statusTexts[$errorCode];
        echo "The meaning of $errorCode is \"$errorConstantName\"".PHP_EOL;

        $errorCode = Response::HTTP_BAD_GATEWAY;
        $errorConstantName = Response::$statusTexts[$errorCode];
        echo "The meaning of $errorCode is \"$errorConstantName\"";

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow  More on the web  Random snippet

  Work with me!