Symfony 2: Generate URL with Full Hostname and Colon and Slashes

Screen Shot 2015-03-05 at 2.09.48 PMSir Tim Berners-Lee has apologized for all of the slashes in the http:// world. But slashes and colons we must have to create a valid web address, and with SSL, we need to know whether it’s http:// or https://.

Fortunately those of us programmers old enough and wise enough to use a wonderful framework like Symfony, generating a valid web address in our source code is easy.

When generating a URL in Symfony, make sure the third parameter for generateUrl is set to TRUE.

$this->generateUrl('name_of_route', array(), true);

As Petar’s comment below says, in Symfony 3, it’s a bit different.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

$this->generateUrl('name_of_route', array(), UrlGeneratorInterface::ABSOLUTE_URL);

That’s a bit cleaner in version 3, and, more readable.

But you folks out there still rolling all of your own custom PHP, I’m sure you can build a valid URL by pulling data out of the $_SERVER hash. If you are one of these sorts of programmers, you should read my post Stop Building Shitty PHP Web Applications.

Screen shot 2015-11-22 at 8.53.10 PM


Share Button

One Comment

Comments are closed.