In a CakePHP (2.3) project, I needed to echo the full (i.e. including scheme (http, https etc) and hostname) current URL in a view. I assumed this would be easy, and it is, but it wasn’t immediately obvious and took a bit of searching. The following examples assume we are on localhost, the project is called ‘project’ and the current page is /controller/action/1, so we would expect the full URL to be: http://localhost/project/controller/action/1.
The way to do it:
All we need to do is to echo a null url, with the ‘full’ option set to true, which means the scheme, hostname and project path are included. As well as null, any “falsey” value seems to work, e.g. false, 0, “”, and even array().
echo $this->Html->url(null, true);
The ways not to do it:
Produces: /project/controller/action/1. This is missing the scheme and hostname.
Produces: /project/controller/action/1. Again, this is missing the scheme and hostname.
echo $this->Html->url( $this->here, true );
Produces: http://localhost/project/project/controller/action/1. Here ‘project’ appears twice, once from $this->here and once as we have set the ‘full’ option to true.
One Reply to “CakePHP: Getting the full URL of the current page”
also you can use Router::url() or Router::url(null, true) anywhere in the cakephp to get the current url.