Scroll to top
© 2022, Empty Code | All Rights Reserved

Get User IP Address using PHP


Rahul Kumar Sharma - October 8, 2019 - 0 comments

Getting a User IP Address using PHP helps to track and monitor users’ activity easily. Sometimes we need to collect the User IP for security.

The Simplest way to get the User IP using $_SERVER['REMOTE_ADDR']

<?php
  echo 'User IP : '.$_SERVER['REMOTE_ADDR'];
?>

If the user using the proxy, the above code will not return the correct IP address. The below code will help to get the correct IP even if the users are using the proxy.

<?php
  echo 'User IP : '.getUserIP();

  function getUserIP(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        $ip = $_SERVER['HTTP_CLIENT_IP']; // IP from Share Internet
    }
    elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // IP pass from Proxy
    }
    else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
  }
?>

Related posts

Post a Comment

Your email address will not be published. Required fields are marked *