0
0
PhpHow-ToBeginner · 3 min read

How to Get IP Address in PHP: Simple Guide

To get the IP address in PHP, use the $_SERVER['REMOTE_ADDR'] variable which contains the client's IP address. For cases behind proxies, check $_SERVER['HTTP_CLIENT_IP'] or $_SERVER['HTTP_X_FORWARDED_FOR'] as fallback options.
📐

Syntax

PHP stores the client's IP address in the $_SERVER superglobal array. The main keys to check are:

  • REMOTE_ADDR: The direct IP address of the client.
  • HTTP_CLIENT_IP: Sometimes set by proxies.
  • HTTP_X_FORWARDED_FOR: A list of IPs when behind proxies.

Use these keys to retrieve the IP address safely.

php
$ip = $_SERVER['REMOTE_ADDR'];
💻

Example

This example shows how to get the user's IP address by checking common server variables and printing it.

php
<?php
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // HTTP_X_FORWARDED_FOR can contain multiple IPs, take the first one
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ipList[0]);
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

$ipAddress = getUserIP();
echo "User IP Address: " . $ipAddress;
?>
Output
User IP Address: 127.0.0.1
⚠️

Common Pitfalls

Many developers only use $_SERVER['REMOTE_ADDR'] which may not work correctly if the user is behind a proxy or load balancer. Also, HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR can be spoofed by the client, so never trust them blindly for security purposes.

Always validate and sanitize IP addresses if you use them for sensitive tasks.

php
<?php
// Wrong way: only using REMOTE_ADDR
$ip = $_SERVER['REMOTE_ADDR'];

// Better way: check all common headers
function getSafeIP() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ipList[0]);
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // Validate IP format
    if (filter_var($ip, FILTER_VALIDATE_IP)) {
        return $ip;
    }
    return 'Unknown IP';
}
?>
📊

Quick Reference

Server VariableDescription
REMOTE_ADDRClient's direct IP address
HTTP_CLIENT_IPIP address from shared internet or proxy
HTTP_X_FORWARDED_FORComma-separated list of IPs from proxies

Key Takeaways

Use $_SERVER['REMOTE_ADDR'] to get the client's IP address in PHP.
Check $_SERVER['HTTP_CLIENT_IP'] and $_SERVER['HTTP_X_FORWARDED_FOR'] for users behind proxies.
Validate IP addresses before using them for security or logging.
Never fully trust proxy headers as they can be spoofed.
Use a function to handle all cases and fallback safely.