How to Retrieve a Client’s IP Address in PHP

Code Snippets Coding Blog Custom Code Snippets PHP PHP Development Tech Tutorials Theme Optimization Tutorials
✨

How to Retrieve a Client’s IP Address in PHP Tutorial/Guide

To find the client's IP address in PHP, you can access the `$_SERVER` superglobal. Here’s a basic way to fetch the IP address of a user visiting your site:

// Basic client IP retrieval
$client_ip = $_SERVER['REMOTE_ADDR'];
echo 'Client IP Address: ' . $client_ip;

This simple method uses `$_SERVER['REMOTE_ADDR']` to return the IP of the request origin. However, when your server is behind a proxy or CDN, this value might reflect the proxy IP instead. To get around this, you can check for forwarded headers like `HTTP_X_FORWARDED_FOR` or `HTTP_CLIENT_IP`. Here's a more complete example:

// Check forwarded headers for accurate 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;

This approach ensures that, if forwarded headers exist, they’ll be prioritized over the default `REMOTE_ADDR`. Alternatively, you can use the `getenv()` function to check environment variables for the IP:

// getUserIP using getenv()
function getUserIP() {
    $ip = getenv('HTTP_CLIENT_IP') ?: 
          getenv('HTTP_X_FORWARDED_FOR') ?: 
          getenv('HTTP_X_FORWARDED') ?: 
          getenv('HTTP_FORWARDED_FOR') ?: 
          getenv('HTTP_FORWARDED') ?: 
          getenv('REMOTE_ADDR');

    $ip_array = explode(',', $ip);
    return trim($ip_array[0]);
}

You can then use the function like this:

$client_ip = getUserIP();
echo 'Client IP Address: ' . $client_ip;

These techniques help ensure more accurate IP retrieval, especially for users behind proxy networks or load balancers.

πŸ’‘ Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.