PHP getting user's IP

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?

*note: the website is not hosted on localhost and im 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;

?>

3 answers

  • answered 2021-05-14 13:45 Europa

    <?php
    // Print IP of user
    $ip = $_SERVER['REMOTE_ADDR'];
    $ip = htmlentities($ip, ENT_COMPAT, "UTF-8");
    echo"$ip";
    
    // You can also get the users hostname
    $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    $hostname = htmlentities($hostname, ENT_COMPAT, "UTF-8");
    echo"$hostname";
    ?>
    

  • answered 2021-05-14 16:46 Elfnan Sherif

    try this code

    $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_X_CLUSTER_CLIENT_IP']))
    $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    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';
    echo $ipaddress;
    

  • answered 2021-05-15 01:05 gstrauss

    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.