How to print visitor’s IP address using PHP code

PHP code to get IP address of the website visitor

In PHP, you can use the $_SERVER superglobal variable to get the IP address of a website visitor. Here is an example of how to get the IP address of a website visitor:

<?php
function getVisitorIP() {
    $ip = '';
    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;
}

$visitor_ip = getVisitorIP();
echo $visitor_ip;
?>


This code uses the $_SERVER['HTTP_CLIENT_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], and $_SERVER['REMOTE_ADDR'] variables to get the IP address of a website visitor.

$_SERVER['HTTP_CLIENT_IP'] – It contains the IP address of the client that is connected to the website. It could be the IP address of the visitor or a proxy server’s IP address.

$_SERVER['HTTP_X_FORWARDED_FOR'] – It contains the IP address of the visitor if the website is behind a proxy or a load balancer. It could contain multiple IP addresses separated by a comma, in which case the first IP address is the visitor’s IP address.

$_SERVER['REMOTE_ADDR'] – It contains the IP address of the visitor. It is used as a fallback if the other two variables are not available.

It’s important to note that the above code is a basic example and it may not work for all cases, for example, if the visitor is behind a VPN or a proxy, the IP address returned may not be the actual IP address of the visitor.

Also, if you are behind a load balancer or a reverse proxy, you need to configure the load balancer or the reverse proxy to pass the real IP address of the visitor to your application.

In addition, it’s important to note that some ISPs use Carrier-grade NAT (CGN) which makes it impossible to get the real IP address of the visitor, in this case, you will only get the IP address of the NAT gateway.

Finally, you can use a service like ipinfo.io to get more information about the visitor’s IP address such as the geolocation, organization, and more.

Leave a Comment