[Symfony] Getting the request referrer

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

It's a widespread need to have to get the referrer of the current request. Of course, it can be done via the Symfony request value object. But it's not so obvious to find. If you came here because you want to know the route name of the referrer you get, you should have a look at this snippet 😉.
[Fun fact] As you can see, the HTTP "referer" header field is misspelt.



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  More on the web  Random snippet

  Work with me!