How to get the client IP address in PHP?

Last updated 5 years, 7 months ago | 1541 views 75     5

Tags:- PHP

$_SERVER['REMOTE_ADDR'] id use to get the IP address of the user.

 

But sometime it may not return the true IP address of the client at all time. Use Below code to get true IP address of user.

<?php

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}

echo getUserIP()

?>