Aug
8
2014
8
2014
Get Actual IP Address with PHP
A snippet by admin
1 Comment
/**
* More reliable function to acquire actual user IP address
* @access public
* @param none
* @return string
*/
function getip()
{
if( isset( $_SERVER ) )
{
if( isset( $_SERVER["HTTP_X_FORWARDED_FOR"] ) )
{
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif( isset( $_SERVER["HTTP_CLIENT_IP"] ) )
{
$realip = $_SERVER["HTTP_CLIENT_IP"];
}
else
{
$realip = $_SERVER["REMOTE_ADDR"];
}
}
else
{
if( getenv( 'HTTP_X_FORWARDED_FOR' ) )
{
$realip = getenv( 'HTTP_X_FORWARDED_FOR' );
}
elseif( getenv( 'HTTP_CLIENT_IP' ) )
{
$realip = getenv( 'HTTP_CLIENT_IP' );
}
else
{
$realip = getenv( 'REMOTE_ADDR' );
}
}
return $realip;
}
1 Comment + Add Comment
Leave a comment
Recent Snippets
- htaccess : Only allow access to specific wordpress upload types if logged in
- MySQL : Query WordPress Database for Invalid Media Filenames
- PHP : Get Actual IP Address with PHP
- JavaScript : Allow Tab in Textarea
- PHP : Clean sanitized database contents on output
- htaccess : Force www. prefix in URIs
- PHP : Force File Download with Correct Content Type
- Wordpress : Disable upgrade notification
I used a similar function for some time. However, it doesn’t always return the correct IP. Some german T-Mobile users are located in the USA having an IP which is assigned to the DoD. Others are located in China or Vietnam. Reason is that T-Mobile assigns an internal IP to their devices and put it in HTTP_X_FORWARDED_FOR. See f.e. https://telekomhilft.telekom.de/t5/Mobiles-Internet/IP-Adressen-aus-USA/m-p/1051709#M2482 or https://telekomhilft.telekom.de/t5/Frage-stellen/T-Mobile-IPs-sind-in-den-USA-verortet/qaq-p/249843/search-sort-type-order/date