How to Implement Fast Offline IP Geolocation in PHP with ip2region

This guide explains the ip2region PHP library, compares its lightweight V2 and full‑featured V3 versions, details installation via Composer, shows project structure, core features, new v3.0 enhancements, and provides step‑by‑step code examples for functional and object‑oriented usage.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
How to Implement Fast Offline IP Geolocation in PHP with ip2region

Introduction

The ip2region library is a high‑performance, PHP‑only IP‑to‑geolocation solution that works offline. It supports both IPv4 and IPv6, requires no external extensions, and runs on PHP 5.4+.

Why Choose Offline IP Lookup?

Using a local database eliminates network latency and third‑party costs, allowing real‑time city‑level visitor location display. The library loads a binary database file locally, making it suitable for traditional IPv4 environments as well as newer IPv6 networks.

Version Selection

V2.0 (lightweight) : IPv4 only, ~10 MB size, ideal for small deployments.

V3.0 (full) : IPv4 + IPv6 support, ~100 MB size, includes enterprise‑grade features such as smart partitioning and compression.

Install the desired version with Composer:

composer require zoujingli/ip2region:^2.0   # V2.0
composer require zoujingli/ip2region:^3.0   # V3.0 (default)

Project Overview

ip2region provides fast microsecond‑level IP queries by leveraging the official XDB format. It manages large database files through automatic sharding and compression, delivering accurate location data for both IPv4 and IPv6.

Core Features

Dual‑protocol support : Automatic detection of IPv4 or IPv6.

High performance : Microsecond‑level response time.

Zero dependencies : Pure PHP implementation compatible with PHP 5.4+.

Custom database paths : Ability to specify your own IPv4/IPv6 database files.

Easy integration : Composer installation and both functional and object‑oriented APIs.

Smart caching : File, VectorIndex, and full‑data cache options.

Partitioned file management : Automatic splitting of large files into < 100 MB chunks.

Intelligent compression : Supports gzip, zip, and zstd with up to 81 % compression ratio.

Enterprise‑grade : Robust error handling, exception management, and performance monitoring.

Lazy loading : Query objects are created on demand to reduce memory usage.

Zero configuration : Auto‑detects database version and format.

Project Structure

ip2region/
├── src/                # Core source files
│   ├── Ip2Region.php   # Main class (IPv4/IPv6 support)
│   ├── XdbSearcher.php # Wrapper for official XDB searcher
│   └── ChunkedDbHelper.php # Helper for partitioned files
├── db/                 # Partitioned database files (auto‑generated)
│   ├── ip2region_v4.xdb.part1   # IPv4 shard
│   └── ip2region_v6.xdb.part*   # IPv6 shards
├── tools/              # Utility scripts
│   ├── split_db.php    # Database sharding tool (important!)
│   ├── ip2region_v4.xdb   # Full IPv4 database (source only)
│   └── ip2region_v6.xdb   # Full IPv6 database (source only)
├── tests/              # Test suite
│   └── demo.php        # Demo program
├── function.php        # Global function entry point
├── composer.json        # Composer configuration
└── README.md           # Documentation

v3.0 New Features

Smart Partition Management

Automatic splitting : Large files are divided into < 100 MB chunks.

Compression support : gzip/zip formats reduce file size by 60‑80 %.

On‑demand merging : First use automatically decompresses and merges shards.

Intelligent cache : Merged files are cached to avoid repeated work.

Memory optimization : Lazy loading creates IPv4/IPv6 query objects only when needed.

Enhanced API

Dual‑protocol function : ip2region() auto‑detects IPv4/IPv6.

Object‑oriented interface : Ip2Region class provides full OOP methods.

Batch query : batchSearch() handles multiple IPs at once.

Performance monitoring : getStats() and getMemoryUsage() report runtime metrics.

Enterprise Features

Error handling : Comprehensive exception messages.

Concurrency safety : Safe for multi‑process/thread usage.

Cache strategies : File, VectorIndex, and full‑data caches.

PHP 5.4+ compatibility : Works on all modern PHP versions.

Quick Start

1. Install via Composer

# Install V3.0 (recommended, full features)
composer require zoujingli/ip2region:^3.0

# Or install V2.0 (lightweight, IPv4 only)
composer require zoujingli/ip2region:^2.0

2. Prepare Database Files

The repository already includes partitioned database files. To use a custom database:

# Download the full database to the tools/ directory
# Generate partitioned files
php tools/split_db.php v4   # IPv4 shards
php tools/split_db.php v6   # IPv6 shards

3. One‑Line Usage

<?php
require 'vendor/autoload.php';

// Simple functional call
echo ip2region('61.142.118.231') . "
"; // 中国广东省中山市【电信】
echo ip2region('2001:4860:4860::8888') . "
"; // 美国加利福尼亚州圣克拉拉【专线用户】

// Specify query method
echo ip2region('61.142.118.231', 'search') . "
"; // 中国|广东省|中山市|电信
echo ip2region('61.142.118.231', 'memory') . "
"; // array format

// Object‑oriented usage
$ip2region = new \Ip2Region();
echo $ip2region->simple('61.142.118.231') . "
";

// Custom database (optional)
$ip2region = new \Ip2Region('file', '/path/to/ip2region_v4.xdb', '/path/to/ip2region_v6.xdb');
echo $ip2region->simple('8.8.8.8') . "
";
?>

4. Verify Installation

# Test IPv4 query
composer test:ipv4

# Test IPv6 query
composer test:ipv6

# Test different query methods
composer test:search   # detailed query
composer test:memory   # memory‑based query

# Query a specific IP
composer query 61.142.118.231
composer query:search 61.142.118.231
composer query:memory 61.142.118.231

# Run demo program
composer demo

Calling the Library in Your Project

Functional Call

<?php
require 'vendor/autoload.php';

// Simple query
echo ip2region('61.142.118.231') . "
"; // 中国广东省中山市【电信】

// Batch query example
$ips = ['61.142.118.231', '114.114.114.114', '2001:4860:4860::8888'];
foreach ($ips as $ip) {
    echo "$ip => " . ip2region($ip) . "
";
}
?>

Object‑Oriented Call

<?php
require 'vendor/autoload.php';

try {
    $ip2region = new \Ip2Region();
    echo $ip2region->simple('61.142.118.231') . "
";
    echo $ip2region->search('2001:4860:4860::8888') . "
";

    // Detailed info
    $info = $ip2region->getIpInfo('61.142.118.231');
    print_r($info);

    // Batch query
    $results = $ip2region->batchSearch(['61.142.118.231', '114.114.114.114']);
    print_r($results);

    // Performance stats
    $stats = $ip2region->getStats();
    echo "Memory usage: " . $stats['memory_usage'] . " bytes
";
    echo "IPv4 loaded: " . ($stats['v4_loaded'] ? 'yes' : 'no') . "
";
    echo "IPv6 loaded: " . ($stats['v6_loaded'] ? 'yes' : 'no') . "
";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "
";
}
?>

Custom Database Configuration

<?php
require 'vendor/autoload.php';

try {
    $ip2region = new \Ip2Region('file', '/path/to/your/ip2region_v4.xdb', '/path/to/your/ip2region_v6.xdb');
    echo $ip2region->simple('8.8.8.8') . "
";

    $customStatus = $ip2region->isUsingCustomDb();
    echo "IPv4 using custom DB: " . ($customStatus['v4'] ? 'yes' : 'no') . "
";
    echo "IPv6 using custom DB: " . ($customStatus['v6'] ? 'yes' : 'no') . "
";

    // Dynamically set new paths
    $ip2region->setCustomDbPaths('/new/path/v4.xdb', '/new/path/v6.xdb');
    $dbInfo = $ip2region->getDatabaseInfo();
    echo "IPv4 path: " . ($dbInfo['custom_v4_path'] ?: 'default partition') . "
";
    echo "IPv6 path: " . ($dbInfo['custom_v6_path'] ?: 'default partition') . "
";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "
";
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPIP geolocationoffline lookupip2region
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.