How to Retrieve IP Geolocation in Java and PHP Using $_SERVER and ip2region
This article explains how to obtain a user's IP address on the server side, use the Taobao IP database or the open‑source ip2region library to map the IP to province and city, and demonstrates integration in Java, PHP and Laravel with sample code and performance details.
Recently many Chinese platforms (Weibo, Toutiao, Tencent, Douyin, Zhihu, Kuaishou, Xiaohongshu, etc.) have started displaying a user's IP location—country for overseas users and province for domestic users—without an option to disable it.
On the server side you can retrieve the client IP using the PHP superglobal $ip = $_SERVER["REMOTE_ADDR"]; and output it with echo $ip; . This obtains the raw IP address from the request headers.
For IP‑to‑location mapping, the Taobao IP library (https://ip.taobao.com/) is a common choice, providing province and city information for Chinese IPs.
The open‑source project ip2region (https://github.com/lionsoul2014/ip2region) offers an offline IP location database with up to 99.9% accuracy by aggregating data from several providers (Taobao, GeoIP, CZ88). It supports multiple language bindings, including Java, C#, PHP, C, Python, Node.js, Golang, Rust, Lua, and Nginx.
binding
描述
开发状态
binary查询耗时
b-tree查询耗时
memory查询耗时
c
ANSC c binding
已完成
0.0x毫秒
0.0x毫秒
0.00x毫秒
c#
c# binding
已完成
0.x毫秒
0.x毫秒
0.1x毫秒
golang
golang binding
已完成
0.x毫秒
0.x毫秒
0.1x毫秒
java
java binding
已完成
0.x毫秒
0.x毫秒
0.1x毫秒
lua
lua实现的binding
已完成
0.x毫秒
0.x毫秒
0.x毫秒
lua_c
lua的c扩展
已完成
0.0x毫秒
0.0x毫秒
0.00x毫秒
nginx
nginx的c扩展
已完成
0.0x毫秒
0.0x毫秒
0.00x毫秒
nodejs
nodejs
已完成
0.x毫秒
0.x毫秒
0.1x毫秒
php
php实现的binding
已完成
0.x毫秒
0.1x毫秒
0.1x毫秒
php5_ext
php5的c扩展
已完成
0.0x毫秒
0.0x毫秒
0.00x毫秒
php7_ext
php7的c扩展
已完成
0.0毫秒
0.0x毫秒
0.00毫秒
python
python bindng
已完成
0.x毫秒
0.x毫秒
0.x毫秒
rust
rust binding
已完成
0.x毫秒
0.x毫秒
0.x毫秒
ip2region v2.0 introduces a standardized region format (country|area|province|city|ISP), automatic data deduplication and compression (the full database is about 11 MiB), and microsecond‑level query latency. Performance can be further improved with a 512 KiB vector index cache or by loading the entire XDB file into memory.
To use ip2region in a Laravel project, install the package via Composer: composer require larva/laravel-ip2region . Then query an IP address with:
$info = \Larva\Ip2Region\Ip2Region::find('218.1.2.3');
var_export($info, true);
// array (
// 'city_id' => 2163,
// 'region' => '中国|华南|广东省|深圳市|鹏博士',
// )Finally, the article encourages readers to like and share if they found the content helpful.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.