How to Get IP Address of User in PHP

Many times we need to collect the visitor IP address to track activity and for security reasons. It’s very easy to get the IP address of visitors in PHP. PHP $_SERVER variable provides an easy way to get user IP address. The $_SERVER contains an array that provides the server and environment-related information in PHP.

The simplest way to get the visitor IP address is using the REMOTE_ADDR indices in PHP $_SERVER method.

  • $_SERVER['REMOTE_ADDR'] – Returns the IP address of the user from which viewing the current page.
echo 'User IP - '.$_SERVER['REMOTE_ADDR'];

But sometimes REMOTE_ADDR does not return the correct IP address of the user. The reason behind this is to use a Proxy or CDN. In that situation, use the following code to get real IP address of user in PHP.

function getUserIpAddr(){
    if(!empty(
$_SERVER['HTTP_CLIENT_IP'])){
        
//ip from share internet
        
$ip $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty(
$_SERVER['HTTP_X_FORWARDED_FOR'])){
        
//ip pass from proxy
        
$ip $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        
$ip $_SERVER['REMOTE_ADDR'];
    }
    return 
$ip;
}

echo 
'User Real IP - '.getUserIpAddr();

11 Comments

  1. Fahad Ullah Said...
  2. Shr Said...
  3. Qaisermehboob Said...
  4. Saurabh Singh Said...
  5. Sachin Mishra Said...
  6. Hamza Said...
  7. Abhishek Said...
  8. UGEN Said...
  9. Satyam Said...
  10. Secret Said...
  11. Wisdom Said...

Leave a reply

keyboard_double_arrow_up