Get Real Visitor IP Address

I use this PHP code to get the visitor’s IP address even though they are using a proxy.

Here my code on

But why return error Use of undefined constant FILTER_VALIDATE - assumed ‘FILTER_VALIDATE’ on line 8 blah blah blah

Hi @pramana0361 and welcome to the forums.

Try this and run the script locally. Notice the @ signs have been removed.

ini_set('display_errors', 'true');

function getUserIP()
    $client  = $_SERVER['HTTP_CLIENT_IP'];
    $forward = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE))
        $ip = $client;
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
        $ip = $forward;
        $ip = $remote;

    return $ip;

$user_ip = getUserIP();

echo $user_ip;

Forgot to mention there is no FILTER_VALIDATE PHP Constant - check the manual.

1 Like

If you are checking if the user is behind a proxy, keep in mind that you do not know if that is the IP of the user.
I can send the same header value with some random IP when I browse your site.

Not to mention that if they use an anonymous proxy, it will not forward their IP at all, or it could as mentioned above forward a random IP.

Due to this, if you look to log information you need to store both IPs, both the IP they access the site through, and any passed proxy IP.

Also, you also want to add $ _ SERVER[‘HTTP_X_CLUSTER_CLIENT_IP’] and $ _ SERVER[‘HTTP_PROXY_USER’] to your list.

Return warning like this:

Warning: Unsupported declare 'strict_types' in C:\xampp\htdocs\test\ip.php on line 2

Notice: Undefined index: HTTP_CLIENT_IP in C:\xampp\htdocs\test\ip.php on line 8

Notice: Undefined index: HTTP_X_FORWARDED_FOR in C:\xampp\htdocs\test\ip.php on line 9

Notice: Use of undefined constant FILTER_VALIDATE - assumed 'FILTER_VALIDATE' in C:\xampp\htdocs\test\ip.php on line 12

Warning: filter_var() expects parameter 2 to be long, string given in C:\xampp\htdocs\test\ip.php on line 12

The strict types is a PHP version 7 thing. If you’re running older than that (for shame) remove that line of code.

And you need to do something about FILTER_VALIDATE there is no such thing

1 Like

Hey, it’s solved.
I have changed this part FILTER_VALIDATE to FILTER_VALIDATE_IP, and now my code work like a charm!

Thank you to all of you.


I often use this script to view the $_SERVER[] parameters.

echo '<pre>';
 print_r( $_SERVER );
echo '</pre>';

This link may be useful because it details why all parameters are NOT shown.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.