Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to get the IP address of visitors on your PHP powered website


Every client that sends a request to your website on the internet has a logical address known as the client’s IPInternet Protocol address. The IP addresses of users that access your website can easily be extracted using built-in functions in PHP.

If you have access to a client’s IP address, you can perform any of the following actions:

  • You can block traffic coming to your site from a set of IP addresses.
  • You can track the users’ activities on your site using their IP addresses.
  • You can also resolve the hostname to an IP address in your code.


Superglobals are inbuilt variables in PHP, predefined and accessible throughout the entire script. As they concern accessibility, they are not scope bound.

Some examples of Superglobals include:

  • $_POST
  • $_GET
  • $_SERVER

$_SERVER superglobal

The $_SERVER superglobal provides header, path, and script location information. It can also accepts several other properties.

How to get a user’s IP

To get a user’s IP address, you can use the superglobal $_SERVER and one of its properties called REMOTE_ADDR.

The syntax to obtain the REMOTE_ADDR property is shown below.


You can use the syntax above to return the IP address of a user on your site, as shown below.

$message ="Your latest visitor is: ";
echo $message, $_SERVER[REMOTE_ADDR];

In the code above, the visitor’s IP address will be displayed on the screen.

Visitors behind a proxy

When a visitor goes through a proxyServers that interface between the client and the destination, the simple command above will require some adjustments.

The code below shows how you can get the IP address of visitors behind a proxy.

function visitorIP() {  
//Check if visitor is from shared network 
  if(!empty($_SERVER['HTTP_CLIENT_IP'])) {  
            $vIP = $_SERVER['HTTP_CLIENT_IP'];  
//Check if visitor is using a proxy 
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){  
            $vIP = $_SERVER['HTTP_X_FORWARDED_FOR'];  
//check for the remote address of visitor.  
          $vIP = $_SERVER['REMOTE_ADDR'];  
  return $vIP;  
$vIP = visitorIP();  
echo 'The visitors Real address : '.$vIP;  


Get the IP address of any website

PHP allows you to do a hostname to IP address translation for any URLUniform Resource Locator by using the gethostbyname() function. However, you need to ensure that you are on the same network as the site’s server.

$ip_address = gethostbyname("");  
echo "IP Address of Wikipedia is - ".$ip_address;  
echo "</br>";  
$ip_address = gethostbyname("");  
echo "IP Address of Educative is - ".$ip_address; 

The code above will return the IP addresses of the web address indicated.



View all Courses

Keep Exploring