php-core / client-ip
dev-master
2024-08-11 14:50 UTC
Requires
- php: >=8.1
This package is auto-updated.
Last update: 2024-09-11 15:08:51 UTC
README
在PHP中获取客户端IP,即使是在CloudFlare、代理或负载均衡器后面。
感谢 https://github.com/yidas/php-client-ip 提供了这个想法,并为类提供了一个基础结构。
安装
在项目中运行Composer
composer require php-core/client-ip
然后在应用的引导(如config文件)中初始化它
require __DIR__ . '/vendor/autoload.php'; ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16'] ]);
配置
示例配置
ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16', '172.217.2.89'], 'headerKeys' => ['HTTP_X_FORWARDED_FOR'], ]);
示例
echo ClientIP::get(); ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16', '172.217.3.11'], 'headerKeys' => ['HTTP_X_FORWARDED_FOR'] ]); echo ClientIP::get();
默认情况下,系统会在运行时缓存IP,要禁用它(例如对于amphp的web服务器),请使用disableCache
ClientIP::config([ 'disableCache' => true ]); echo ClientIP::get();
如果客户端IP是203.169.1.37
,以下是一些通过上述示例代码演示的连接情况
负载均衡器正常网络
您的服务器位于负载均衡器后面并处于私有网络中。
ClientIP::config([ 'proxyIPs' => true ]);
将proxyIPs
设置为true
表示所有请求都通过负载均衡器,这将始终获取转发IP,与上述设置相同
ClientIP::config([ 'proxyIPs' => ['0.0.0.0/32'] ]);
来自服务器的结果
192.168.0.10 //Before setting the config
203.169.1.37 //After setting the config, get the forward IP
代理可选网络
如果您的服务器在公共网络中,不仅直接接收请求,还支持通过信任代理进行访问
ClientIP::config([ 'proxyIPs' => ['172.217.3.11'] ]);
来自服务器的结果
- 方式1:客户端直接连接到服务器
203.169.1.37 //Before setting the config
203.169.1.37 //The request IP is not from proxyIPs, so identify as a Client.
- 方式2:客户端通过代理连接到服务器
172.217.3.11 //Before setting the config
203.169.1.37 //The request IP comes from proxyIPs, get the forward IP.
讨论
从Web服务器实现
另一种获取真实IP的方式是在Web服务器端实现它
许可证
MIT