Skip to content

Instantly share code, notes, and snippets.

@mintindeed
Created February 22, 2014 19:23
Show Gist options
  • Save mintindeed/9160648 to your computer and use it in GitHub Desktop.
Save mintindeed/9160648 to your computer and use it in GitHub Desktop.
Yet another helper method for getting a user's real IP address
<?php
class IP {
/**
* Helper method for validating the IP address.
* Handled IPv4 and filters out private and reserved ranges.
* @param $ip_address string
* @return $ip_address bool|string Returns false if invalid
*/
protected function _validate_ip( $ip_address ) {
return filter_var( $ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE );
}
/**
* Get the user's real ip address
* Change which $_SERVER variables to check for via add_filter( 'pmc_helpdesk_ip_keys' )
* @return $possible_ip bool|string Returns false if no valid IP is found
*/
protected function _get_user_ip() {
$possible_ip_keys = apply_filters( 'pmc_helpdesk_ip_keys', array(
'True-Client-IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_REAL_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
) );
foreach ( $possible_ip_keys as $possible_ip_key ) {
if ( ! isset($_SERVER[$possible_ip_key]) ) {
continue;
}
if ( strpos( $_SERVER[$possible_ip_key], ',' ) !== false ) {
$possible_ips = explode( ',', $_SERVER[$possible_ip_key] );
foreach ( $possible_ips as $possible_ip ) {
$possible_ip = trim( $possible_ip );
$possible_ip = $this->_validate_ip( $possible_ip );
if ( $possible_ip ) {
return $possible_ip;
}
}
} else {
$possible_ip = $this->_validate_ip( $_SERVER[$possible_ip_key] );
if ( $possible_ip ) {
return $possible_ip;
}
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment