#### 方案一: --- 參考文章:[https://www.php.cn/php-weizijiaocheng-406174.html](https://www.php.cn/php-weizijiaocheng-406174.html) ``` // 客戶端真實(shí)的IP地址 function get_real_ip() { $ip = false; // 客戶端IP 或 NONE if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $ip = $_SERVER["HTTP_CLIENT_IP"]; } // 多重代理服務(wù)器下的客戶端真實(shí)IP地址(可能偽造),如果沒有使用代理,此字段為空 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']); if ($ip) { array_unshift($ips, $ip); $ip = false; } for ($i = 0; $i < count($ips); $i++) { if (!eregi ("^(10│172.16│192.168).", $ips[$i])) { $ip = $ips[$i]; break; } } } // 客戶端IP 或 (最后一個(gè))代理服務(wù)器 IP return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); } ``` #### 方案二: --- ```php /** * 獲取客戶端IP */ public function get_real_ip() { $ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) { foreach ($matches[0] AS $xip) { if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) { $ip = $xip; break; } } } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) { $ip = $_SERVER['HTTP_X_REAL_IP']; } return $ip ? $ip : '127.0.0.1'; } ```