function to get user IP address in Yii

yii
30,322

Solution 1

try this:

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

instead

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

with "()" it should work

Solution 2

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

Share:
30,322
user2636556
Author by

user2636556

Updated on March 18, 2020

Comments

  • user2636556
    user2636556 about 4 years

    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

  • Nana Partykar
    Nana Partykar over 8 years
    Great One. :) :) This answer only i was looking for. Thanku
  • tread
    tread almost 8 years
    Another way is:Yii::app()->request->userHostAddress
  • Ibrahim.H
    Ibrahim.H about 6 years
    even shorter: Yii::$app->request->userIP;.