Get a user’s IP address with PHP — the most accurate way.

Written by
Published
Updated
Typical Read
3 minutes

Getting an IP address from a visitor can be difficult due to spoofing — ExpressVPN being one of the most popular spoofers. Learn the most accurate way get an IP address with PHP below.

Savvy or extra cautious visitors can easily spoof their IP address. This can make getting accurate geolocation or user tracking data difficult. There’s not a 100% way of ensuring an IP address is accurate, but there is a 99.9% way. It will not protect you from the 0.1% of malicious users looking to abuse your system by injecting their own request headers.

tl;dr

<?php
/**
 * Return the current visitor's IP address.
 * 
 * @since x.x.x
 * @link https://www.benmarshall.me/get-ip-address/
 * 
 * @return string|false The current visitor's IP address, false if unavailable.
 */
if ( ! function_exists( 'get_ip_address' ) ) {
  function get_ip_address() {
    foreach([
      'HTTP_CLIENT_IP', 
      'HTTP_X_FORWARDED_FOR', 
      'HTTP_X_FORWARDED', 
      'HTTP_X_CLUSTER_CLIENT_IP', 
      'HTTP_FORWARDED_FOR', 
      'HTTP_FORWARDED', 
      'REMOTE_ADDR'
    ] as $key ) {
      if ( array_key_exists( $key, $_SERVER ) === true ) {
        foreach( explode( ',', $_SERVER[ $key ] ) as $ip_address ) {
          $ip_address = trim( $ip_address );
          if ( filter_var( 
            $ip_address, 
            FILTER_VALIDATE_IP, 
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false 
          ) {
            return $ip_address;
          }
        }
      }
    }
  }
}

When the client connects to a web server the IP address gets assigned by using one of the HTTP headers. RFC 7239 standard specifies the Forwarded headers. Many proxy servers and caching engines use also nonstandard but adopted by practice the X-Forwarded-For HTTP header field to assign a comma and space-separated values of IP addresses (first one is the originating client).

Saving an IP to a database? If you are going to save the IP address to a database as a string, make sure you have space for at least 45 characters. IPv4 is being replaced by a newer IPv6, which has a maximum length of 39 characters and IPv4-mapped IPv6 address has a maximum length of 45 characters. More and more servers are now getting the IPv6 and those addresses are larger than the older IPv4 addresses.

Get a User’s IP Address with PHP — the most accurate way.

The function above checks all possible IP address $_SERVER variables in order of importance to attempt to get the most accurate IP address for a visitor:

  1. HTTP_CLIENT_IP

  2. HTTP_X_FORWARDED_FOR

  3. HTTP_X_FORWARDED

  4. HTTP_X_CLUSTER_CLIENT_IP

  5. HTTP_FORWARDED_FOR

  6. HTTP_FORWARDED

  7. REMOTE_ADDR

Once an IP address is retrieved from one of the variables above, it cleans and verifies before returning it. Just remember, there’s no guarantee that it’s going to be 100% accurate, but 99.9% is just as good. And why not just use REMOTE_ADDR?

REMOTE_ADDR and why it’s not perfect.

Using REMOTE_ADDR is the simplest way to get a visitor’s IP address, however, sometimes it’s not correct. There’s a number of reasons why:

  • The user is behind a proxy
  • Your apache server is behind a reverse proxy (e.g. varnish)

REMOTE_ADDR will work, but using the function above is ideal if you want to be super cautious about getting the most accurate IP address — and why wouldn’t you want to. Gathering IP data for tracking or site protection should always be as accurate as possible.

Using Cloudflare? When using Cloudflare as a stacked CDN or proxy, use the variable $_SERVER["HTTP_CF_CONNECTING_IP"] instead of $_SERVER["REMOTE_ADDR"].

Frequently Asked Questions

What is an IP address?

An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing.

How do you get a user’s IP address with PHP?

For most situations, $_SERVER[‘REMOTE_ADDR’] will do the trick. Though there is a more accurate way since REMOTE_ADDR may not always return the actual IP address of a visitor.

What can you do with a user’s IP address?

IP addresses are useful if you need geolocation capabilities on your site. For example, if you want to display the weather to a user for their region, you can use the client IP address to determine their location and show the weather for their city or region. You can also restrict content from displaying in certain geographic regions or filter content displayed.

Get an IP address with PHP

Join the conversation.

Your email address will not be published. Required fields are marked *

All comments posted on 'Get a user’s IP address with PHP — the most accurate way.' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.