How to get client IP address in PHP: the correct solution
Hello everyone! I'm a beginner PHP developer and I've encountered a problem with getting the real IP address of my site's visitors. I need to log IPs for spam protection and analytics.\n\nThe problem is that I'm using $_SERVER['REMOTE_ADDR'], but when the site is behind Cloudflare or an Nginx proxy, this method returns the proxy server's IP instead of the real user's IP. I've tried different options, but they all seem unreliable.\n\nHere's my current code:\n```php\n$ip = $_SERVER['REMOTE_ADDR'];\nif (!empty($_SERVER['HTTP_CLIENT_IP'])) {\n $ip = $_SERVER['HTTP_CLIENT_IP'];\n} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {\n $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];\n}\necho "Your IP: " . $ip;\n```\n\nBut I've heard that HTTP headers can be spoofed, and an attacker can send a fake IP. How ca
No answers yet.
Log in to leave an answer