Function to get user IP address in Yii

I am trying to create a shortcut s to get the IP address of the user, I created this function below in protected / helpers / shortcut.php

echo getIP(); function getIP() { return CHttpRequest::getUserHostAddress(); } 

I get this error because I set my php.ini to strict. and getUserHostAddress () is not a static function

 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 

I tried

 Yii::app()->request->userHostAddress; 

but i get this error

 Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/dev/protected/helpers/shortcuts.php on line 97 

any idea what am i doing wrong? Thanks

+7
yii
source share
2 answers

try the following:

 Yii::app()->request->getUserHostAddress() 

instead

 Yii::app()->request->getUserHostAddress 

with "()" it should work

+13
source share

In Yii2, use Yii::$app->getRequest()->getUserIP()

+37
source share

All Articles