Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

php - Getting base URL in Yii 2

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?

question from:https://stackoverflow.com/questions/27856533/getting-base-url-in-yii-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get base URL of application you should use yiihelpersUrl::base() method:

use yiihelpersUrl;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...