Get base URL in Yii console application

How to get base URL in Yii CConsoleApplication ?

I tried Yii::app()->request->getBaseUrl(true) and ended up with the following error.

Undefined index: SERVER_NAME (/var/www/yii/framework/web/CHttpRequest.php:279)

+7
source share
5 answers

There is no request object in the console application. The request object in the web application is an instance of CHttpRequest , if you create URLs in a standalone task, you need to configure baseUrl in some other way, possibly in the configuration:

 "request" => array( 'hostInfo' => 'http://localhost', 'baseUrl' => '/yii-project/index-test.php', ), // OR 'request' => array( 'hostInfo' => 'http://localhost', 'baseUrl' => '/yii-project', 'scriptUrl' => 'index-test.php', ), 
+13
source

For the Yii2 extended template, create a params.php file if it does not exist in the config directory of your console or regular application and paste the following code:

 return [ 'frontendUrl' => 'http://yourdomain.com' ]; 

So that you can access it in the console as follows:

 echo Yii::$app->params['frontendUrl']; 
+3
source

You should add config / console.php to the component array

 'request' => array( 'hostInfo' => 'http://localhost', 'baseUrl' => '', 'scriptUrl' => '', ), 

and also add urlManager so that it removes index.php? r = site / action from url and you will have nice urls.

 'urlManager' => array( 'urlFormat' => 'path', 'showScriptName' => false, 'rules' => array( '<controller:\w+>' => '<controller>/index', '<controller:\w+>/<id:\d+>' => '<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>' => '<controller>/<action>', ), ), 
0
source

Please try the following way to get the base page of the url,

 echo Yii::app()->getBaseUrl(true); 
-3
source

get home url:

http: //www.demo.local

 echo Yii::app()->homeUrl; 
-3
source

All Articles