How to get complete current url for Cakephp

How do you echo out current URL in Cake's view?


Solution 1:

You can do either

From a view file:

<?php echo $this->request->here() ?>">

Which will give you the absolute url from the hostname i.e. /controller/action/params

Or

<?php echo Router::url(null, true) ?> 

which should give you the full url with the hostname.

Solution 2:

I prefer this, because if I don't mention "request" word, my IDE gives warning.

<?php echo $this->request->here; ?>

API Document: class-CakeRequest


Edit: To clarify all options

Current URL: http://example.com/en/controller/action/?query=12

// Router::url(null, true)
http://example.com/en/controller/action/

// Router::url(null, false)
/en/controller/action/

// $this->request->here
/en/controller/action/

// $this->request->here()
/en/controller/action/?query=12

// $this->request->here(false)
/en/controller/action/?query=12

// $this->request->url
en/controller/action

// $_SERVER["REQUEST_URI"]
/en/controller/action/?query=12

// strtok($_SERVER["REQUEST_URI"],'?');
/en/controller/action/

Solution 3:

<?php echo $_SERVER[ 'REQUEST_URI' ]; ?>

EDIT: or,

<?php echo $this->Html->url( null, true ); ?>

Solution 4:

The following "Cake way" is useful because you can grab the full current URL and modify parts of it without manually having to parse out the $_SERVER[ 'REQUEST_URI' ] string and then manually concatenating it back into a valid url for output.

Full current url:
Router::reverse($this->request, true)

Easily modifying specific parts of current url:
1) make a copy of Cake's request object: $request_copy = $this->request

2) Then modify $request_copy->params and/or $request_copy->query arrays

3) Finally: $new_url = Router::reverse($request_copy, true).

Solution 5:

Cakephp 3.5:

echo $this->Url->build($this->getRequest()->getRequestTarget());

Calling $this->request->here() is deprecated since 3.4, and will be removed in 4.0.0. You should use getRequestTarget() instead. $this->request is also deprecated, $this->getRequest() should be used.