How to get the client's IP address in PHP? (code example)

青灯夜游
Release: 2023-04-04 13:08:02
forward
2150 people have browsed it

The content of this article is to introduce how PHP obtains the client’s IP address? (Code example), let everyone know how to obtain the IP address in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First let’s understand the meaning ofrelated variables:

$_SERVER['REMOTE_ADDR']:Browse the current page The ip address of the user's computer

$_SERVER['HTTP_CLIENT_IP']:The client's ip

$_SERVER['HTTP_X_FORWARDED_FOR']:The gateway of the user's computer browsing the current page

$_SERVER['HTTP_X_REAL_IP']:nginx proxy mode, Obtain the client's real IP

Let'sintroduce the method of obtaining the client's IP address in PHP through a simple code example.

/** * 获取客户端IP地址 */ function 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; }
Copy after login

Summary:The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of How to get the client's IP address in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!