This article mainly introduces the encapsulation class for PHP to obtain client and server IP. It briefly analyzes the basic usage of PHP using server predefined variables and performs a simple encapsulation. Friends who need it can refer to it
The details are as follows:
Client IP related variables:
1. $_SERVER['REMOTE_ADDR']; Client IP, which may be the user’s IP, It may also be the proxy IP.
2. $_SERVER['HTTP_CLIENT_IP']; The IP of the agent may exist and can be forged.
3. $_SERVER['HTTP_X_FORWARDED_FOR']; Which IP the user uses as a proxy may exist and can be forged.
Server-side IP related variables:
1. $_SERVER["SERVER_NAME"] needs to be obtained using the function gethostbyname(). This variable displays correctly on both the server and client sides.
2. $_SERVER["SERVER_ADDR"], tested on the server side: 127.0.0.1 (this is related to the setting value of BindAddress in httpd.conf). The test results on the client are correct.
The categories are as follows:
class getIP{ function clientIP(){ $cIP = getenv('REMOTE_ADDR'); $cIP1 = getenv('HTTP_X_FORWARDED_FOR'); $cIP2 = getenv('HTTP_CLIENT_IP'); $cIP1 ? $cIP = $cIP1 : null; $cIP2 ? $cIP = $cIP2 : null; return $cIP; } function serverIP(){ return gethostbyname($_SERVER["SERVER_NAME"]); } } $getIP = new getIP(); $clientIp = getIP::clientIP(); $serverIp = getIP::serverIP(); echo 'Client IP is ',$clientIp,'<br />'; echo 'Server IP is ',$serverIp,'<br />';
Examples of PHP conforming to PSR programming specifications
##
The above is the detailed content of PHP implements encapsulation class to obtain client and server IP. For more information, please follow other related articles on the PHP Chinese website!