Friday 26 June 2015

Get visitor IP in PHP PHP

It is simple to get the visitor's IP in PHP, just using the $_SERVER['REMOTE_ADDR'] variable.
- Example:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
echo 'Your IP is: '. $ip;
?>
But this method is not 100% sure. There are some servers that return the server IP when using $_SERVER['REMOTE_ADDR']. Not know why, maybe because they are behind of a proxy, or some server setings.

Generally, to get the user IP, on most servers it can be used the variable presented above, but if returns the IP of the server, there is also another way, the function presented below.
This function returns the visitor IP (even if the $_SERVER['REMOTE_ADDR'] contains the server IP) because it gets the IP from $_SERVER['HTTP_X_FORWARDED_FOR'].
Just add it in your script, and call it when you need (like in the example below).
// Function to get the user /visitor IP in PHP ( http://coursesweb.net/ )
function getUserIP() {
  $ip = $_SERVER['REMOTE_ADDR'];
  if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ip = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
  }
  return $ip;
}
- Example:
<?php
// Function to get the user /visitor IP in PHP ( http://coursesweb.net/ )
function getUserIP() {
  $ip = $_SERVER['REMOTE_ADDR'];
  if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ip = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
  }
  return $ip;
}

// Cals the getUserIP() function, and output the IP
$ip = getUserIP();
echo $ip;
?>

0 comments:

Post a Comment