c5_labsci/web/admin/demo/dyn/realip.php
2026-01-27 00:52:00 +08:00

80 lines
2.9 KiB
PHP

<?php
namespace web\admin\demo\dyn;
class realip {
public static function json_realip() {
$post = new \ciy\post();
$headers = explode("\n", $post->get('header'));
$server = array();
foreach ($headers as $header) {
$ind = strpos($header, '=');
if ($ind === false)
continue;
$server[strtoupper(substr($header, 0, $ind))] = substr($header, $ind + 1);
}
$ret['ip'] = self::simip($server);
return succjson($ret);
}
public static function json_getip() {
$ret['ip'] = getip();
return succjson($ret);
}
static function simip($server) {
$headers = [
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_TRUE_CLIENT_IP', // Akamai/Cloudflare
'HTTP_X_FORWARDED_FOR', // 最常用的代理头
'HTTP_FORWARDED', // RFC 7239 标准
'HTTP_X_REAL_IP', // Nginx
'HTTP_FORWARDED_FOR', // 变体
'HTTP_X_FORWARDED', // 旧格式
];
$ips = array();
foreach ($headers as $header) {
if (!empty($server[$header])) //$_SERVER
$ips[] = strtolower($server[$header]);
}
foreach ($ips as $ip) {
$ind = strpos($ip, ',');
if ($ind !== false)
$ip = substr($ip, 0, $ind);
$ind = strpos($ip, 'for=');
if ($ind !== false) {
//for=192.0.2.43:47011,for="[2001:db8:cafe::17]:47011",for=unknown
//for=_hidden, for=_SEVKISEK
$ip = substr($ip, $ind + 4);
if ($ip[0] == '"') {
$ip = substr($ip, 1, strpos($ip, '"', 1) - 1);
$ind = strpos($ip, ']');
if ($ind !== false)
$ip = substr($ip, 1, $ind - 1);
} else if ($ip[0] == '[') {
$ip = substr($ip, 1, strpos($ip, ']') - 1);
} else {
$ind = strpos($ip, ';');
if ($ind !== false)
$ip = substr($ip, 0, $ind);
if (strpos($ip, '.') !== false) {
$ind = strpos($ip, ':');
if ($ind !== false)
$ip = substr($ip, 0, $ind);
}
}
} else {
if (strpos($ip, '.') !== false) {
$ind = strpos($ip, ':');
if ($ind !== false)
$ip = substr($ip, 0, $ind);
}
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))
return $ip;
}
if (isset($_SERVER['REMOTE_ADDR']))
return $_SERVER['REMOTE_ADDR'];
return '0.0.0.0';
}
}