Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current relative URL in Symfony2 service?

Tags:

php

symfony

Pretty much as simple as the title says. Really what I mean is how can I get the current relative URL, including the file name if there is one, i.e everything emphasised below:

http://hostname/app/app_dev.php/path/to/some/action?even=a%20query%20string
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Now, this is easy enough if you don't need the file, you get the RequestStack, get the current request and use something like this in a service:

$request->getPathInfo();

But in my current example within this question that would bring back the following:

/path/to/some/action?even=a%20query%20string

Without the /app_dev.php, which is the important part for me currently. The other alternative I have already exhausted is using the router to generate the current route, which does work nicely in some ways, it does show the file name, but there are some other issues in that if some part of the query string that isn't defined in the routing is included in the current request then it wouldn't show up in the result from this.

So, let's pretend in my above example again that the even query string wasn't included in the routing, I couldn't generate that and this method would just return something like this:

/app_dev.php/path/to/some/action

Which is of course, still not ideal.

So, how can I go about getting everything I'm looking for here, reliably?

like image 957
Seer Avatar asked Jan 22 '26 15:01

Seer


2 Answers

This was actually a lot simpler than I thought. All I had to use was:

$request->getRequestUri();

And it returns exactly what I was looking for.

like image 170
Seer Avatar answered Jan 24 '26 11:01

Seer


You can check what's the Symfony environment is as @sjagr says; but if you still need to get the section of full path without checking Symfony environment you can do something like:

//After you send RequestStack to your service and assume you assign it to $this->request
$url = $this->Request->getUri();
$pieces = parse_url($url);
$looking_for_section = substr($pieces['path'], strrpos(strstr($pieces['path'], '.', true), '/')) . $pieces['query'];

Hopefully it helps you

like image 22
Javad Avatar answered Jan 24 '26 11:01

Javad