Base_url in CakePHP

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

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

Is there an alternative? Is there any global variable available to get the base url, not this?

+28
php cakephp
Nov 28 '10 at 7:22
source share
5 answers

Yes there is. In your opinion, you can access:

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

In addition, your host information is stored in the variable $_SERVER['HTTP_HOST'] if you want to.

In your controller, if you want to get the full URL, use this:

 Router::url('/', true); 
+64
Nov 28 '10 at 19:54
source share

Use any option below.

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

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

  • <?php echo $this->base;?>

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

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

and create a common assistant with the following functions

 <?php class CommonHelper extends AppHelper { function get_url($url){ return BASE_URL.$url; } function get_src($url){ echo BASE_URL.$url; } } ?> 

and use anywhere in the project

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

Do not forget to include the general assistant in the controller

I recommend method 2 and 5 because they give the full url.

+26
Dec 01
source share

Use Router::url('/', true) anywhere in the application.
In particular, in the view, you can use $this->Html->url('/', true) (or any other Helper, 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.

+9
Nov 29 '10 at 4:26
source share

you can use

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

.

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

+9
Nov 05 '13 at 6:40
source share

For most purposes, I would suggest using CakePHP HtmlHelper to create URLs, so you don't have to worry about the base URL. However, the most user-friendly way to get the base URL in your view would be <?php echo $html->webroot; ?> <?php echo $html->webroot; ?> .

+1
Nov 29 '10 at 10:34
source share



All Articles