Skip to main content

We share with you the useful PHP function for getting user's IP address you could use in your projects.

The easiest way for obtaining visitor's IP address is using the code line:

- Advertisement -

<?php
 
echo $_SERVER["REMOTE_ADDR"]
 
?>

However, if the user is located behind a proxy server, the code may not work, so you can use our function:

<?php
 
/*
* Function returns visitors IP address
*
*/
function GetVisitorIP() { 
  if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
  }
  else {
    $ip_address=$_SERVER['REMOTE_ADDR'];
  }
 
  return trim($ip_address);
}
  
?>

And use it in the code in the following way:

<?php
 
$users_ip_address = GetVisitorIP();
 
?>

- Advertisement -
- Advertisement -