Determining the Client's IP Address in PHP
The PHP superglobal array $_SERVER provides access to various server-related information, including the client's remote IP address via $_SERVER['REMOTE_ADDR']. However, this approach may fall short in specific scenarios.
In cases where the $_SERVER['REMOTE_ADDR'] value is incorrect, alternative server variables can be employed to acquire the IP address accurately. The following explore two approaches:
Using getenv() Function:
The getenv() function retrieves the value of an environment variable. It can be utilized to obtain the client's IP address as follows:
function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; }
Using $_SERVER Superglobal Array:
The $_SERVER array contains HTTP request information. The following code demonstrates its use in obtaining the IP address:
function get_client_ip() { $ipaddress = ''; if (isset($_SERVER['HTTP_CLIENT_IP'])) $ipaddress = $_SERVER['HTTP_CLIENT_IP']; else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; else if(isset($_SERVER['HTTP_X_FORWARDED'])) $ipaddress = $_SERVER['HTTP_X_FORWARDED']; else if(isset($_SERVER['HTTP_FORWARDED_FOR'])) $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; else if(isset($_SERVER['HTTP_FORWARDED'])) $ipaddress = $_SERVER['HTTP_FORWARDED']; else if(isset($_SERVER['REMOTE_ADDR'])) $ipaddress = $_SERVER['REMOTE_ADDR']; else $ipaddress = 'UNKNOWN'; return $ipaddress; }
Both approaches provide equivalent functionality but differ in how they access the information.
The above is the detailed content of How Can I Accurately Determine a Client's IP Address in PHP?. For more information, please follow other related articles on the PHP Chinese website!