'function to get user IP address in Yii

I'm trying to create a s shortcut to get user IP address, 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 i'm doing wrong? Thanks

yii


Solution 1:[1]

try this:

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

instead

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

with "()" it should work

Solution 2:[2]

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

Solution 3:[3]

This is related to Yii2 (but may work in Yii 1.1 too). If you need the "X-Forwarded-For" IP instead of the Proxy, if your server is behind a reserve proxy, make the change the 'request' configuration on config/main.php as below:

'request' => [
    'csrfParam' => '_csrf-frontend',
    'trustedHosts' => [
        '192.168.1.10', // The IP of the reverse proxy server
    ],
    'secureHeaders' => [ // The headers coming from reserve proxy
        'X-Forwarded-For',
        'X-Forwarded-Proto',
        'Front-End-Https',
    ],
],

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3410311
Solution 2 S B
Solution 3 ns16