How to Get User IP Address in PHP and JavaScript


This page demonstrates two popular approaches to retrieve a users IP address. using PHP (server-side) and JavaScript (client-side). Whether you are building a web application that needs to track visitor locations or implement security features. This guide will show you how to retrieve the user's IP address using both PHP and JavaScript.

Get User IP Address in PHP

In PHP, you can use the $_SERVER superglobal to retrieve the user's IP address securely. Here is the function to fetch the IP, even if the user is behind a proxy:

PHP
<?php
function getUserIP() {
    // Check for shared internet connections (e.g., Cloudflare, proxy)
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Handle multiple IPs if forwarded through proxies
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ipList[0]); // Get the first real IP
    } else {
        $ip = $_SERVER['REMOTE_ADDR']; // Default method
    }

    return $ip;
}
?>

Usage:

PHP
<?php
// Usage
$userIP = getUserIP();
echo "User IP Address: " . $userIP;
?>

Advanced User IP Detection - Secure Client Identification for PHP Applications

This function accurately detects client IP addresses in PHP applications, even behind proxies and CDNs. It checks multiple HTTP headers in priority order, validates IPs for proper formatting, and includes a helper function to identify private networks. This secure implementation prevents common spoofing techniques while supporting major services like Cloudflare and Akamai.

PHP
<?php
/**
 * Get the real user IP address considering various headers and proxy scenarios.
 *
 * @return string|null The user's IP address or null if no valid IP was found
 */
function getUserIP() {
    // Define trusted headers in order of reliability
    $headers = [
        'HTTP_CF_CONNECTING_IP',    // Cloudflare specific
        'HTTP_TRUE_CLIENT_IP',      // Akamai and some CDNs
        'HTTP_CLIENT_IP',           // Direct client IP
        'HTTP_X_REAL_IP',           // Nginx proxy
        'HTTP_X_FORWARDED_FOR',     // Common proxy header
        'HTTP_X_FORWARDED',         // Common proxy header variant
        'HTTP_FORWARDED_FOR',       // RFC 7239
        'HTTP_FORWARDED',           // RFC 7239
        'REMOTE_ADDR'               // Direct connection (fallback)
    ];

    // Check each header
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            // Handle comma-separated lists (for X-Forwarded-For etc.)
            if (strpos($_SERVER[$header], ',') !== false) {
                // Get the first IP in the list (most reliable client IP)
                $ips = explode(',', $_SERVER[$header]);
                $ip = trim($ips[0]);
            } else {
                $ip = trim($_SERVER[$header]);
            }

            // Validate the IP format
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }

    // Fallback if no valid IP found through headers
    return null;
}

/**
 * Check if an IP is in a private/reserved range.
 *
 * @param string $ip IP address to check
 * @return bool True if IP is in a private/reserved range
 */
function isPrivateIP($ip) {
    return !filter_var(
        $ip,
        FILTER_VALIDATE_IP,
        FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
    );
}
PHP
<?php
$userIP = getUserIP();
if ($userIP) {
    // Valid IP found
    if (isPrivateIP($userIP)) {
        // Handle private IP scenario
    }
} else {
    // No valid IP found
}

Private Networks and Their Significance

Private networks use specific IP address ranges reserved for local networks that aren't routable on the public internet. These include:

  • 10.0.0.0/8 (10.0.0.0 to 10.255.255.255) - Used for large corporate networks
  • 172.16.0.0/12 (172.16.0.0 to 172.31.255.255) - Medium-sized networks
  • 192.168.0.0/16 (192.168.0.0 to 192.168.255.255) - Home and small office networks
  • 127.0.0.0/8 (127.0.0.0 to 127.255.255.255) - Localhost / loopback addresses

Why Detecting Private IPs Matters

Identifying private IPs is crucial for security because:

  1. Spoofing Prevention: Attackers may try to submit private IPs to bypass security measures
  2. Proxy Verification: Helps determine if a request is coming through a legitimate proxy
  3. Accurate Logging: Ensures you're not recording internal network addresses as public visitors
  4. Geolocation Accuracy: Private IPs shouldn't be used for geolocation services

The isPrivateIP() function in our implementation uses PHP's built-in filtering to detect these private ranges, helping you implement appropriate security policies for requests originating from internal networks.

Get User IP Address in JavaScript

In JavaScript, we cannot directly get the user's IP address using vanilla JS because it runs in the browser. However, we can use external services like https://api64.ipify.org?format=json to fetch the IP.

Method 1: Using Fetch API

JavaScript
fetch('https://api64.ipify.org?format=json')
  .then(response => response.json())
  .then(data => console.log("User IP Address:", data.ip))
  .catch(error => console.error("Error fetching IP:", error));

Method 2: Using XMLHttpRequest (Older Method)

JavaScript
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api64.ipify.org?format=json", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);
    console.log("User IP Address:", response.ip);
  }
};
xhr.send();

Method 3: Using jQuery (If Available)

JavaScript
$.getJSON("https://api64.ipify.org?format=json", function(data) {
    console.log("User IP Address:", data.ip);
});

Get Geolocation from IP Address

In addition to retrieving the IP address, you can also get geolocation details such as the user's city, region, country, and coordinates. This is useful for customizing user experiences, enforcing location-based restrictions, or analytics.

Get Geolocation in PHP

Using ipinfo.io:

PHP
<?php
function getUserGeolocation($ip) {
    $url = "https://ipinfo.io/{$ip}/json";
    $response = file_get_contents($url);
    return json_decode($response, true);
}

// Get IP
$ip = getUserIP();
$locationData = getUserGeolocation($ip);

echo "User IP: " . $locationData['ip'] . "<br>";
echo "City: " . $locationData['city'] . "<br>";
echo "Region: " . $locationData['region'] . "<br>";
echo "Country: " . $locationData['country'] . "<br>";
echo "Location (Lat, Long): " . $locationData['loc'];
?>

Get Geolocation in JavaScript

Using ipinfo.io with javaScript:

JavaScript
fetch('http://ip-api.com/json/')
  .then(response => response.json())
  .then(data => {
    console.log("User IP:", data.query);
    console.log("City:", data.city);
    console.log("Region:", data.regionName);
    console.log("Country:", data.country);
    console.log("Latitude:", data.lat);
    console.log("Longitude:", data.lon);
  })
  .catch(error => console.error("Error fetching geolocation:", error));

Both PHP and JavaScript offer ways to retrieve the user's IP address. PHP is ideal for server-side processing, while JavaScript relies on external APIs to fetch the IP in the browser. Additionally, you can retrieve geolocation details to provide more context about the user's location. Choose the method that best suits your needs!

Get Geolocation via User Input IP Address with JavaScript and PHP

Sometimes, you may want to retrieve geolocation details for a specific IP address entered by the user. This can be useful for checking information about any IP rather than just the visitor's IP.

Demo: IP Geolocation Finder


JavaScript Implementation

Here is how you can build a simple JavaScript solution using ip-api.com that allows users to input an IP address and get location details:

⚠️ Note: If you are using JavaScript-based solutions, APIs like http://ip-api.com/json/ work only over HTTP connections. They will not work on HTTPS due to mixed content restrictions. To ensure compatibility, use a PHP-based request like the one provided below.

HTML
<h2>IP Geolocation Lookup</h2>
<input type="text" id="ipInput" placeholder="Enter IP Address" />
<button onclick="getGeoLocation()">Get Location</button>
<p id="result"></p>
JavaScript
async function getGeoLocation() {
    const ip = document.getElementById("ipInput").value.trim();
    const result = document.getElementById("result");

    if (!ip) {
        result.innerText = "Please enter a valid IP address.";
        return;
    }

    const API_URL = `http://ip-api.com/json/${ip}`;

    try {
        result.innerText = "Fetching location data...";
        const response = await fetch(API_URL);
        const data = await response.json();

        if (data.status === "fail") {
            result.innerText = "Invalid IP Address or API Error. "+data.message;
            return;
        }

        result.innerText = `
            IP: ${data.query}\n
            City: ${data.city}\n
            Region: ${data.regionName}\n
            Country: ${data.country}\n
            Latitude: ${data.lat}, Longitude: ${data.lon}
        `;
    } catch (error) {
        console.error("Error fetching geolocation:", error);
        result.innerText = "An error occurred while fetching the data.";
    }
}

How It Works:

  1. The user enters an IP address into the input field.
  2. Clicking the "Get Location" button triggers a fetch request to ip-api.com.
  3. If the IP is valid, the response provides geolocation details.
  4. The results are displayed on the page.

This is a simple and effective way to fetch geolocation data for a user-inputted IP address.

PHP Implementation

Here is how you can build a simple PHP solution using ip-api.com that allows users to input an IP address and get location details without refreshing the page using JavaScript Fetch API:

HTML
<h2>IP Geolocation Lookup</h2>
<input type="text" id="ipInput" placeholder="Enter IP Address" required>
<button onclick="getGeoLocation()">Get Location</button>
<div id="result"></div>
JavaScript
async function getGeoLocation() {
    const ip = document.getElementById("ipInput").value.trim();
    const result = document.getElementById("result");

    if (!ip) {
        result.innerText = "Please enter a valid IP address.";
        return;
    }

    const API_URL = `geolocation.php?ip=${ip}`;

    try {
        result.innerText = "Fetching location data...";
        const response = await fetch(API_URL);
        const data = await response.json();

        if (data.status === "fail") {
            result.innerText = "Error: " + data.message;
            return;
        }

        result.innerHTML = `
            <p><strong>IP:</strong> ${data.query}</p>
            <p><strong>City:</strong> ${data.city}</p>
            <p><strong>Region:</strong> ${data.regionName}</p>
            <p><strong>Country:</strong> ${data.country}</p>
            <p><strong>Latitude:</strong> ${data.lat}, <strong>Longitude:</strong> ${data.lon}</p>
        `;
    } catch (error) {
        console.error("Error fetching geolocation:", error);
        result.innerText = "An error occurred while fetching the data.";
    }
}

PHP Script

Create a separate PHP file geolocation.php to handle API requests:

PHP
<?php
    header('Content-Type: application/json');

    // Exit early if no IP is provided
    if (!isset($_GET['ip'])) {
        echo json_encode(['status' => 'fail', 'message' => 'No IP address provided']);
        exit;
    }

    $ip = trim($_GET['ip']);
    // Basic input validation
    $ip = filter_var($ip, FILTER_VALIDATE_IP);
    if ($ip === false) {
        echo json_encode(['status' => 'fail', 'message' => 'Invalid IP address format']);
        exit;
    }

    $api_url = "http://ip-api.com/json/" . urlencode($ip);

    // Use file_get_contents with error suppression
    $response = @file_get_contents($api_url);

    // Check if the request was successful
    if ($response !== false) {
        echo $response;
    } else {
        echo json_encode(['status' => 'fail', "message" => "Failed to retrieve IP data."]);
    }

Download all the codes as a zip file.

Download zip file

How It Works:

  1. The user enters an IP address into the input field.
  2. Clicking the "Get Location" button triggers a JavaScript fetch() request.
  3. The request is sent to a PHP script (geolocation.php), which fetches the geolocation data.
  4. The response is displayed on the page without requiring a page refresh.

This method ensures a seamless experience while maintaining HTTPS compatibility.

API Documentation ip-api.com