PHP to calculate the real IP address of a client behind a proxy
<?php
// Check for a reverse proxy header.
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Get the IP address from the reverse proxy header.
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
// Get the IP address from the HTTP_CLIENT_IP header.
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
// Get the IP address from the REMOTE_ADDR header.
$ip = $_SERVER['REMOTE_ADDR'];
}
// Check if the IP address is a private IP address.
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
// The IP address is not a private IP address.
echo "Your public IP address is $ip.";
} else {
// The IP address is a private IP address.
echo "Your IP address is $ip. This is a private IP address, so your real public IP address is not available.";
}
?>
Explanation:
This code uses the following steps to calculate the real IP address of a client behind a proxy:
- It checks for the presence of the
HTTP_X_FORWARDED_FOR
header. This header is typically set by reverse proxies and contains the IP address of the client that made the original request. - If the
HTTP_X_FORWARDED_FOR
header is not present, it checks for the presence of theHTTP_CLIENT_IP
header. This header is typically set by proxies and contains the IP address of the client that made the request to the proxy. - If neither the
HTTP_X_FORWARDED_FOR
nor theHTTP_CLIENT_IP
header is present, it uses theREMOTE_ADDR
header. This header contains the IP address of the client that made the request to the web server. - It checks if the obtained IP address is a private IP address using the
filter_var()
function. A private IP address is an IP address that is not routable on the public Internet. - If the IP address is not a private IP address, it is considered the public IP address of the client.
- If the IP address is a private IP address, it is assumed that the client is behind a proxy and its real public IP address is not available.
How to implement effectively:
To implement this code effectively, you should use it in conjunction with other security measures to prevent spoofing of IP addresses. For example, you could use a combination of IP address validation, rate limiting, and user authentication to ensure that only legitimate users are able to access your website or application.