[Symfony] Getting the request referer

Published on 2019-11-20 • Modified on 2019-11-20

It's a very common need to have to get the referer of the current request. Of course, it can be done via the Symfony request value object. But it's not so obvious to find. So, here is the code. If you came here because you want to know the route name of the referer you get, you should have a look at this snippet 😉.

<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

 * 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 Snippet57Trait
    public function snippet57(Request $request): void
        // If you hit the run button, the referer will be the URL of this snippet.

        echo $request->headers->get('referer'); // That's it! 😁

 Run this snippet  More on Stackoverflow  Random snippet