Skip to content

Instantly share code, notes, and snippets.

@alessioalex
Created November 4, 2011 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alessioalex/1339202 to your computer and use it in GitHub Desktop.
Save alessioalex/1339202 to your computer and use it in GitHub Desktop.
PHP get real IP
function get_real_ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
// check if isset REMOTE_ADDR and != empty
elseif(isset($_SERVER['REMOTE_ADDR']) && ($_SERVER['REMOTE_ADDR'] != '') && ($_SERVER['REMOTE_ADDR'] != NULL))
{
$ip = $_SERVER['REMOTE_ADDR'];
// you're probably on localhost
} else {
$ip = "127.0.0.1";
}
return $ip;
}
@clyfe
Copy link

clyfe commented Nov 4, 2011

The "if" approach is somewhat flawed. Better have a configuration file and check a "proxied = 1" flag, because with the current state of things if your app is proxied and for some reason the "HTTP_X_FORWARDED_FOR" header is not set (nothing to forward ?) instead of returning NULL the function will return the proxy's IP.

@alessioalex
Copy link
Author

I wanted some general approach for this, since I'm not aware of the server-settings of the user that installs the app (on his own server / shared hosting).
I guess you made the "proxied = 1" suggestion considering I own the server right?

@clyfe
Copy link

clyfe commented Nov 4, 2011

Nevertheless it should be an app setting toggled depending on the deployment type imho.
I guess the current things should do if it's not mission critical and you're trying to make things simple for the owner.

@alessioalex
Copy link
Author

Thanks for giving me the heads-up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment