Skip to content
Advertisement

Get Ip From Client Apache and Php

Want to ask, but maybe this question is a duplicate. I’m sorry that all the answers to the other questions didn’t work in my case.

Question

I have a server with apache as webserver running php+7.4 with default settings and certbot as SSL with public IP 192.168.1.11, I want to retrieve the IP of the client that opens my website, for example the domain news.test.com. test.com domain itself has a public ip address example 123.100.1.10. how do i get the client ip that opens the news.test.com domain?

Already do

I already do this to get IP

public static function get_ip() {
    $mainIp = '';
    if (getenv('HTTP_CLIENT_IP'))
        $mainIp = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $mainIp = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $mainIp = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $mainIp = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $mainIp = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $mainIp = getenv('REMOTE_ADDR');
    else
        $mainIp = 'UNKNOWN';
    return $mainIp;
}

Problem

Problem I got was not the IP client I got but instead got the IP from the test.com domain. I have tried another internet connection and did a public IP test, but I still get the IP from test.com not the client IP, Is it because the settings from my parent domain or from my apache are in the wrong settings? or there is an error or other way to get the client IP.?

Advertisement

Answer

Please have a try with HTTP_CF_CONNECTING_IP

    public static function get_ip() {
    $mainIp = '';
    if (getenv('HTTP_CF_CONNECTING_IP'))
        $mainIp = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $mainIp = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $mainIp = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $mainIp = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $mainIp = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $mainIp = getenv('REMOTE_ADDR');
    else
        $mainIp = 'UNKNOWN';
    return $mainIp;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement