Getting base URL in Yii 2

后端 未结 10 2437
孤独总比滥情好
孤独总比滥情好 2020-12-30 19:32

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()->getBa         


        
相关标签:
10条回答
  • 2020-12-30 20:14

    You can reach your base URL by this:

    Yii::$app->request->baseUrl
    
    0 讨论(0)
  • 2020-12-30 20:14

    Try below code. It should work. It will return base URL name

    use yii\helpers\Url;

    Url::home('http') // http://HostName/ OR Url::home('https') // https://HostName/

    0 讨论(0)
  • 2020-12-30 20:16

    Use it like this:

    Yii::$app->getUrlManager()->getBaseUrl()
    

    More information on base, canonical, home URLs: http://www.yiiframework.com/doc-2.0/yii-helpers-url.html

    0 讨论(0)
  • 2020-12-30 20:19

    In yii 1 this code return the hostname

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

    In yii2 the following

    Yii::$app->getBaseUrl();
    

    not exists as method of Yii::$app and it triggers an error with message

    Calling unknown method: yii\web\Application::getBaseUrl() 
    

    You could use Request class that encapsulates the $_SERVER

    Yii::$app->request->hostInfo
    
    0 讨论(0)
  • 2020-12-30 20:23

    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.

    0 讨论(0)
  • 2020-12-30 20:25

    I searched for a solution how we can do like in codeigniter, routing like e.g.

    base_url()
    base_url('profile')
    base_url('view/12')
    

    Only way we can do that in Yii2

    <?=Url::toRoute('/profile') ?>
    
    0 讨论(0)
提交回复
热议问题