Skip to Content
Menu

get_ip_address()

Safely retrieve the IP address.

PHP August 7, 2020

Usage

PHP
nebula()->get_ip_address($anonymize)

Parameters

$anonymize
(Optional) (Boolean) Return an anonymized IP address
Default: true

Parameter Notes

Note that the anonymize parameter defaults to true! If you are processing non-anonymized IP addresses you must first have consent from the user to comply with privacy regulations such as the GDPR.

Request or provide clarification »

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

    Located in /libs/Utilities/Utilities.php on line 52.

    No Hooks

    This function does not have any filters or actions available. Request one?
    PHP
            public function get_ip_address($anonymize=true){
                static $memoized = array(); //Prepare to memoize the output so it only has to be calculated once or twice (depending on anonymization)
                $memoize_key = ( $anonymize )? 'anonymized' : 'full';
                if ( array_key_exists($memoize_key, $memoized) ){
                    return $memoized[$memoize_key];
                }
    
                //Return a local IP during WP CLI
                if ( $this->is_cli() ){
                    $memoized[$memoize_key] = '127.0.0.1';
                    return $memoized[$memoize_key];
                }
    
                $ip_keys = array(
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_REAL_IP',
                    'HTTP_CLIENT_IP',
                    'HTTP_X_FORWARDED_FOR',
                    'HTTP_X_FORWARDED',
                    'HTTP_X_CLUSTER_CLIENT_IP',
                    'HTTP_FORWARDED_FOR',
                    'HTTP_FORWARDED',
                    'REMOTE_ADDR'
                );
    
                $server = array_change_key_case($this->super->server, CASE_UPPER);
    
                foreach ( $ip_keys as $ip_key ){
                    if ( array_key_exists($ip_key, $server) ){
                        foreach ( explode(',', $server[$ip_key]) as $ip ){
                            $ip = trim($ip);
    
                            if ( filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) ){
                                $memoized[$memoize_key] = ( !empty($anonymize) )? wp_privacy_anonymize_ip($ip) : $ip;
                                return $memoized[$memoize_key];
                            }
                        }
                    }
                }
    
                return null;
            }
    

    Override

    This function can not be short-circuited with an override filter. Request one?