Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting base URL in Yii 2

Tags:

php

yii

yii2

I am trying to get the base URL for the project in Yii 2 but it doesn't seem to work. According to this page you used to be able to do:

Yii::app()->getBaseUrl(true); 

In Yii 1, but it seems that that method in Yii 2 no longer accepts a parameter?

I've tried doing it without true, such as:

Yii::$app->getBaseUrl(); 

But it just returns empty.

How can you do this in Yii 2?

like image 362
Brett Avatar asked Jan 09 '15 08:01

Brett


People also ask

How can I get base URL in Yii?

Meaning you can just do: Yii::$app->urlManager->baseUrl .

How can I change base URL in Yii?

You can edit /path/to/application/protected/config/main. php to change the default value. Add a request component, and configure baseUrl porperty.

What is $App in Yii?

Applications are objects that govern the overall structure and lifecycle of Yii application systems. Each Yii application system contains a single application object which is created in the entry script and is globally accessible through the expression \Yii::$app .


2 Answers

My guess is that you need to look at aliases.

Using aliases would be like:

Yii::getAlias('@web'); 

You can also always rely on one of these two:

Yii::$app->homeUrl;  Url::base(); 
like image 22
DiegoCoderPlus Avatar answered Oct 05 '22 23:10

DiegoCoderPlus


To get base URL of application you should use yii\helpers\Url::base() method:

use yii\helpers\Url;  Url::base();         // /myapp Url::base(true);     // http(s)://example.com/myapp - depending on current schema Url::base('https');  // https://example.com/myapp Url::base('http');   // http://example.com/myapp Url::base('');       // //example.com/myapp 

Url::home() should NOT be used in this case. Application::$homeUrl uses base URL by default, but it could be easily changed (for example to https://example.com/myapp/home) so you should not rely on assumption that it will always return base URL. If there is a special Url::base() method to get base URL, then use it.

like image 139
rob006 Avatar answered Oct 05 '22 23:10

rob006