Created
November 4, 2011 12:11
-
-
Save alessioalex/1339202 to your computer and use it in GitHub Desktop.
PHP get real IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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?
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.
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
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.