How to Get Client IP Address in PHP?

As a website owner, many times you may need to get the visitor’s IP address. Because it is very important for validation, security, spam prevention, etc. Getting the visitor’s IP address is very easy work in PHP. In this blog, I am going to show you how to get the client IP address in PHP very easily.

In PHP, we can get the visitor’s IP address in the following two ways,

  • getenv() is used to get the value of an environment variable in PHP.
  • $_SERVER is an array contains server variables created by the web server.

Get visitor’s IP address using getenv():

function get_client_ip_by_getenv() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
echo get_client_ip_by_getenv();

Get visitor’s IP address using $_SERVER:

function get_client_ip_by_server() {
    $ipaddress = '';
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
echo get_client_ip_by_server();

Note: This would work only on the live site, because on your localhost your IP would be one of the internal IP addresses, like

Hope this helps.

One Comment on “How to Get Client IP Address in PHP?”

  1. In localhost it returns as you said, but in live server I get only only my external (dynamic) ip in both cases, instead my client’s ip.

Leave a Reply

Your email address will not be published. Required fields are marked *