Open In App

How to get IP Address of clients machine in PHP ?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An IP address is used to provide an identity to a device connected to a network. IP address stands for Internet Protocol address. An IP address allows to track the activities of a user on a website and also allows the location of different devices that are connected to the network to be pinpointed and differentiated from other devices. 

There are two ways to get the IP Address of the client’s machine in PHP. One way is to use the $_SERVER variable and another way is by using the getenv() function.

$_SERVER Variable: It fetches the IP address of the machine from which the request was sent to the webserver. It is an array created by the Apache webserver. Bypassing REMOTE_ADDR in the $_SERVER variable gives the IP address of the client. Sometimes we won’t get an IP address using REMOTE_ADDR because when the user is from the proxy network, REMOTE_ADDR cannot be fetched.

In this case, PHP provides two other variables HTTP_CLIENT_IP and  HTTP_X_FORWARDED_FOR which are passed in $_SERVER to get an IP address.

getenv() function: The other way to get the IP address of the client is using the getenv() function. It is used to retrieve the value of an environment variable in PHP. To get the IP address of the user we need to pass the REMOTE_ADDR variable to the getenv() function.

Syntax:the 

 getenv("REMOTE_ADDR");

Example 1: Let us look into a sample program to fetch the client’s IP address.

PHP




<?php  
    // if user from the share internet  
    if(!empty($_SERVER['HTTP_CLIENT_IP'])) {  
        echo 'IP address = '.$_SERVER['HTTP_CLIENT_IP'];  
    }  
    //if user is from the proxy  
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
        echo 'IP address = '.$_SERVER['HTTP_X_FORWARDED_FOR'];  
    }  
    //if user is from the remote address  
    else{  
        echo 'IP address = '.$_SERVER['REMOTE_ADDR'];  
    }    
?>


Output:

Your IP Address is ::1

Example 2: Below code will give the IP Address of clients machine:

PHP




<?php
    echo "IP Address of client " . getenv("REMOTE_ADDR");
?>


Output:

IP Address of client ::1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads