Home » Php » base_url in CakePHP

base_url in CakePHP

Posted by: admin November 29, 2017 Leave a comment


In most web applications we need global var base_url. In cakephp to get base_url currently i put the following code on beforeRender method in app_controller.php

function beforeRender(){
    $this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));

Is there any alternative? Means is there any global variable available to get the base url rather than this?


Yes, there is. In your view, you may access:

<?php echo $this->webroot; ?>

Also, your host information is stored in the $_SERVER['HTTP_HOST'] variable in case you want that.

In your controller, if you want full URLs, use this:

Router::url('/', true);


Use anyone option below

  1. <?php echo $this->Html->url('/');?>

  2. <?php Router::url('/', true); ?>

  3. <?php echo $this->base;?>

  4. <?php echo $this->webroot; ?>

  5. Define constant in Config/core.php as define("BASE_URL", "www.yoursite.com/"); and use BASE_URL anywhere in your project

and create a common helper with following functions

class CommonHelper extends AppHelper {

    function get_url($url){
        return BASE_URL.$url;

    function get_src($url){
        echo BASE_URL.$url;

and use anywhere in project


<a href="<?php $this->Common->get_src('users/login');?>">login</a>

Don’t forgot to include Common helper in controller

I recommend method 2 and 5 because they give complete url.


Use Router::url('/', true) anywhere in your app.
Specifically in the View, you can use $this->Html->url('/', true) (or any other Helper in fact, the Helper::url method is inherited by all Helpers), which is just a wrapper for the above Router method.

In either case, the second true parameter causes it to return the full URL.


You may use

<?php echo Router::fullbaseUrl();?>

as well.

Refer http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html for more details.


For most purposes I’d suggest using the CakePHP HtmlHelper to generate URLs, that way you won’t need to worry about the base URL. The most user friendly way of getting the base URL in your view, however, would be <?php echo $html->webroot; ?>.