How to get the Client’s IP Address using PHP?

Last updated on August 17, 2023

We can use the ‘REMOTE_ADDR’ from the super global variable $_SERVER to get the client’s IP address. The $_SERVER is the super global variable containing an array that holds information about the client such as headers, paths, and script locations. It is supported by PHP versions 4.1.0, PHP 5, PHP 7, and PHP 8.

echo $_SERVER['REMOTE_ADDR'];

The REMOTE_ADDR might display an inaccurate client’s IP address, especially when we run PHP through a proxy or load balancer.

Run PHP through a Proxy or Load Balancer:

But how to get a client’s IP address when running PHP through a Proxy or Load Balancer?

In this case, we can use the HTTP_X_FORWARDED_FOR header from the $_SERVER super global variable.

if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    echo $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    echo $_SERVER['REMOTE_ADDR'];
}

In the above script, the if-statement checks if HTTP_X_FORWARDED_FOR header exists and it is not empty then it is returning the client’s IP address. Otherwise, the client’s IP address will be getting through the REMOTE_ADDR index. This approach can help us to get the client’s IP address in both situations.

Local Web Server:

This REMOTE_ADDR index returns IP address ::1 on the local web server. It is because ::1 is the IPv6 loopback address for the local machine, which corresponds to 127.0.0.1 in IPv4.

get client's ip address php

Conclusion:

This article demonstrates that client’s IP address can be get through the REMOTE_ADDR index from the $_SERVER super global variable. Also, it explained the way to get the client’s IP address when running PHP code through a proxy or load balancer.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP,