How to get the client IP address in PHP?

Spread the love

Sometimes, we want to get the client IP address in PHP.

In this article, we’ll look at how to get the client IP address in PHP.

How to get the client IP address in PHP?

To get the client IP address in PHP, we can use various values from the $_SERVER associative array.

For instance, we write

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

to get the client IP address from the entry with key 'HTTP_CLIENT_IP' in server.

If that’s not set, then we use the entry with key 'HTTP_X_FORWARDED_FOR'.

Otherwise, we get the client IP address from the $_SERVER entry with key 'REMOTE_ADDR'.

Conclusion

To get the client IP address in PHP, we can use various values from the $_SERVER associative array.

Leave a Reply

Your email address will not be published.