In PHP, obtaining a client's IP address is essential for tasks like logging and access control. The IP address helps identify the user or device accessing the application. $_SERVER['REMOTE_ADDR'] is the primary variable used to retrieve this information.

When an application is behind a proxy or load balancer, $_SERVER['REMOTE_ADDR'] may not return the correct IP address. To handle such cases, checking $_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['HTTP_CLIENT_IP'] is necessary. These variables store the original IP address when a request passes through proxies.

Using the correct server variables ensures accurate IP address retrieval. This accuracy is important for implementing security measures and maintaining proper logs in your application.

Steps to get the client IP address using PHP

  1. Use $_SERVER['REMOTE_ADDR'] to get the client's IP address.
    $client_ip = $_SERVER['REMOTE_ADDR'];
    echo "Client IP Address: " . $client_ip;
  2. If using a proxy or load balancer, check $_SERVER['HTTP_X_FORWARDED_FOR'].
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $client_ip = $_SERVER['REMOTE_ADDR'];
    }
    echo "Client IP Address: " . $client_ip;
  3. If $_SERVER['HTTP_X_FORWARDED_FOR'] is empty, then check $_SERVER['HTTP_CLIENT_IP']..
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $client_ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $client_ip = $_SERVER['REMOTE_ADDR'];
    }
    echo "Client IP Address: " . $client_ip;
Discuss the article:

Comment anonymously. Login not required.