How to Get Client IP Address in PHP?

In the website, many times we 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 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():

<?php
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');
    else
        $ipaddress = 'UNKNOWN';
 
    return $ipaddress;
}

echo get_client_ip_by_getenv();

Get visitor’s IP address using $_SERVER:

<?php
function get_client_ip_by_server() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $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 127.0.0.1.

Hope this helps you.

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

  1. In localhost it returns 127.0.0.1 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 *