Socce Socce -5 years ago 340
PHP Question

Generate absolute URL with specific scheme in Symfony2

I want to generate an absolute URL with a specific scheme (https) in a Symfony2 controller. All the solutions I found point me to configure the targeted route so that it requires that scheme. But I need the route to remain accessible in http, so I can't set it to require https (in which case http requests are redirected to the corresponding https URL).

Is there a way to generate an URL with, in the scope of that URL generation only, a specific scheme?

I saw that using the

keyword generates a "network path"-style URL, which looks like "//"; so maybe I can simply do

'https:' . $this->generateUrl($routeName, $parameters, 'network')

But I don't know if this will be robust enough to any route or request context.

UPDATE: after investigation in the URL generation code, this "network path" workaround seems fully robust. A network path is generated exactly as an absolute URL, without a scheme before the "//".

Answer Source

According to the code or documentation, currently you cannot do that within the generateUrl method. So your "hackish" solution is still the best, but as @RaymondNijland commented you are better off with str_replace:

$url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters));

If you want to make sure only one occurrence is replaced, you can write:

$url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters), 1);

If you want to make sure it's changed only at the beginning of the string, you can write:

$url = preg_replace('/^http:/', 'https:', $this->generateUrl($routeName, $parameters));

No, the colon (:) has no special meaning in the regex so you don't have to escape it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download