函数获取Yii中的用户IP地址

use*_*556 11 yii

我正在尝试创建获取用户IP地址的快捷方式,我在protected/helpers/shortcut.php中创建了这个函数

echo getIP();
function getIP()
{
    return CHttpRequest::getUserHostAddress();
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误,因为我将我的php.ini设置为严格.和getUserHostAddress()不是静态函数

Strict Standards: Non-static method CHttpRequest::getUserHostAddress() should not be called statically in /Applications/XAMPP/xamppfiles/htdocs/dev/protected/helpers/shortcuts.php on line 97
::1
Run Code Online (Sandbox Code Playgroud)

我试过了

Yii::app()->request->userHostAddress;
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误

Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/dev/protected/helpers/shortcuts.php on line 97
Run Code Online (Sandbox Code Playgroud)

我知道我做错了什么?谢谢

S B*_*S B 46

在Yii2中,使用 Yii::$app->getRequest()->getUserIP()

  • 甚至更短:`Yii :: $ app-> request-> userIP;`. (6认同)

小智 16

试试这个:

Yii::app()->request->getUserHostAddress()
Run Code Online (Sandbox Code Playgroud)

代替

Yii::app()->request->getUserHostAddress
Run Code Online (Sandbox Code Playgroud)

用"()"它应该工作