Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the current URL with current port number in Symfony2?

Tags:

url

symfony

Is there a function in Symfony 2.7 which returns the current absolute URL with the current port number?

like image 413
ZugZwang Avatar asked Nov 08 '16 16:11

ZugZwang


3 Answers

The Request object holds both URI and port. So from within a Controller you can

public function indexAction(Request $request)
{
    $uri = $request->getUri();
    $port = $request->getPort();
}

If you're not in a Controller make sure to inject the RequestStack in your class an then fetch uri and port from the master-request

$requestStack->getMasterRequest()->getUri();
like image 108
simon.ro Avatar answered Nov 03 '22 04:11

simon.ro


Generating an absolute url should include the port.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
...

public function indexAction(Request $request)
{
    $link = $this->generateUrl(
        'route_name', [
            'route'=>'params'
        ],
        UrlGeneratorInterface::ABSOLUTE_URL
    );

    return $this->render('template', [
        'link' => $link;
    ]);
}
like image 9
Chase Avatar answered Nov 03 '22 04:11

Chase


You can directly use {{ app.request.uri }} in your twig template.

Ex: If current URI is http://www.example.com:8080/page?q=test&p=2 then {{ app.request.uri }} will return the same string.

like image 4
Tsounabe Avatar answered Nov 03 '22 04:11

Tsounabe