How to Set Base URL in Yii Framework

2020-06-16 02:01发布

When I do

print_r(Yii::app()->request->baseUrl)

I get an empty string. A post on the Yii forum says this is blank by default. How can I change its default value so that I can use absolute URLs?

7条回答
神经病院院长
2楼-- · 2020-06-16 02:07

As the post in that forum says, it might be different for different platforms, or if the web app isnt located in the default folder.
All these things work for me:

echo Yii::app()->request->baseUrl."<br/>" ;
print_r(Yii::app()->request->baseUrl);
echo "<br/>";
var_dump(Yii::app()->getBaseUrl(true));
echo "<br/>";
echo Yii::app()->request->getBaseUrl(true);

I used yiic to create the web app, with default settings using the following command in a terminal, yiic webapp /path/to/webapp
So that generates the necessary directory structure for the web app, and also the default skeleton files. Try it and then see how it works. I'm new to yii myself.

Edit:

This solution might have worked for the op, but the correct way baseUrl can be set is shown by ecco's answer to this question.

查看更多
Deceive 欺骗
3楼-- · 2020-06-16 02:09

try echo Yii::$app->baseUrl(true)
Note that the true parameter is what does the needful.

查看更多
该账号已被封号
4楼-- · 2020-06-16 02:19

It's most likely blank because your bootstrap file (index.php) is at your web root. If it wasn't, you should see some value. Changing it would defeat it's purpose.

You would use like:

href="<?php echo 'http://www.myhost.com' . Yii::app()->request->baseUrl; ?>/css/screen.css"

which for most cases wouldn't change the path, but if you did, say, decide to put your Yii app inside a subdirectory, then it would be portable. (Simply remove the http method and hostname above to make it work on the same host the user is on.)

查看更多
smile是对你的礼貌
5楼-- · 2020-06-16 02:26

Yii::app()->baseUrl returns just a relative Path from the url to index.php for example: 127.0.0.1/index.php returns '' 127.0.0.1/yii/index.php returns '/yii'

查看更多
来,给爷笑一个
6楼-- · 2020-06-16 02:27

Using Yii 2.0.13.1 the below code is working fine

<?php echo Yii::$app->request->baseUrl; ?>
查看更多
虎瘦雄心在
7楼-- · 2020-06-16 02:30

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

return array(
    ...
    'components' => array(
        ...
        'request' => array(
            'baseUrl' => 'http://www.example.com',
        ),
    ),
);
查看更多
登录 后发表回答