I tried this function but this always return the host/website’s IP address instead of the user’s IP any idea why and how to fix it?
the website is not hosted on localhost and I’m using lighttpd to host the website
<?php function getUserIpAddr(){ if(!empty($_SERVER['HTTP_CLIENT_IP'])){ $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } $ip = getUserIpAddr(); echo $ip; ?>
Advertisement
Answer
lighttpd provides the remote address in the CGI environment variable REMOTE_ADDR
.
lighttpd does not set HTTP_CLIENT_IP
unless the request provides Client-IP
header. lighttpd does not set HTTP_X_FORWARDED_FOR
unless the request provides X-Forwarded-For
header.
Among the headers you are using, only REMOTE_ADDR
is trustable. You should never trust data controlled by the client. If your setup has intermediate proxies which set headers such as X-Forwarded-For
, and you trust the intermediate proxies, AND your server can not be reached by anything other than trusted proxies, then those headers can be trusted, too.
If your setup is behind a trusted proxy and you want to use X-Forwarded-For
, then see lighttpd mod_extforward, which can parse X-Forwarded-For
or standardized headers such as Forwarded
, to put the upstream remote address into REMOTE_ADDR
for you. lighttpd mod_extforward also supports the HAProxy PROXY
protocol.