If like me, you are a fan of fast websites and you happen to use a reverse proxy in your environment, you may be having trouble getting the correct IP address to show up in WordPress when people leave comments or perform other actions.
This problem is certainly not new, but I was having some trouble finding a consistent way to get a user’s IP address to display in my environment, which has multiple layers of proxies.
I decided to write my own function to get the correct IP address in all scenarios, even if Cloudflare was disabled, or if access was via the local network. All I had been seeing before was the IP address of the proxy on the docker network, which was insufficient.
Here is the function, place this code at the bottom of your wp-config.php file and you shall always see real IP addresses stored in the REMOTE_ADDR environment variable, and in turn shown in WordPress.
// Set Proper IP frank_set_proper_IP(); function frank_set_proper_IP() { $ip_addr = null; // Check for Cloudflare if ( ! empty($_SERVER['HTTP_CF_CONNECTING_IP']) ) { $ips = explode(',', $_SERVER['HTTP_CF_CONNECTING_IP']); $ip_addr = trim($ips[0]); } // Check X-Real-IP header (non standard) elseif ( ! empty($_SERVER['X_REAL_IP']) ) { $ip_addr = trim($_SERVER['X_REAL_IP']); } elseif ( ! empty($_SERVER['HTTP_X_REAL_IP']) ) { $ip_addr = trim($_SERVER['HTTP_X_REAL_IP']); } // Check X-Forwarded-For elseif ( ! empty($_SERVER['X_FORWARDED_FOR']) ) { $ips = explode(',', $_SERVER['X_FORWARDED_FOR']); $ip_addr = trim($ips[0]); } elseif ( ! empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) { $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $ip_addr = trim($ips[0]); } $_SERVER['REMOTE_ADDR'] = $ip_addr; }
No comment yet, add your voice below!