How to Sanitize user IP?

If the IP value returned from your server has a special character,
you can use:wp_statistics_sanitize_user_ipfilter in your WordPress for getting real user IP from your $_SERVER.

For example:
If your $_SERVER: 192.000.000.1, 192.000.000.2, 192.000.000.3
And your real IP is: 192.000.000.1
You can use a final filter like this:

add_filter( 'wp_statistics_sanitize_user_ip', 'sanitize_user_ip' );
function sanitize_user_ip( $user_ip ) {
    $ip_list = explode( ",", $user_ip );
    $user_ip = trim( $ip_list[0] );

    return $user_ip;
}

Or if your $_SERVER: for=192.000.000.1;proto=http;host=site.com
And your real IP is: 192.000.000.1
Use this one:

add_filter( 'wp_statistics_sanitize_user_ip', 'sanitize_user_ip' );
function sanitize_user_ip( $user_ip ) {
    $regex = '/(?<=for=).*?(?=;)/';
    preg_match( $regex, $user_ip, $ip );
    $user_ip = $ip[0];

    return $user_ip;
}

You can add each code on top of your activate theme functions.php.

Leave Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.