You are here: Home / Topics / How to get the client IP address in PHP

How to get the client IP address in PHP

Filed under: PHP on 2023-06-30 06:24:56

In this tutorial, we are going to see how to get the client IP address in PHP. We often need to collect the client’s IP address to track activity and for security reasons. It is very easy to get the IP address of the visitor in PHP. The PHP variable $_SERVER makes it easy to get the IP address of the user.

The easiest way to get the IP address of the visitor is to use REMOTE_ADDR in PHP.

$_SERVER[‘REMOTE_ADDR’] – Returns the IP address of the user from which the current page is displayed.
 

Example 1: How to get the client IP address in PHP


<?php
 echo 'The client\'s IP address is : '.$_SERVER['REMOTE_ADDR'];
?>


Output:

The client's IP address is : 192.168.1.101
Sometimes REMOTE_ADDR does not return the correct IP address for the user. The reason behind this is the use of a Proxy. In this case, use the following code to get the user’s real IP address in PHP.

Example 2: How to get the client IP address in PHP


<?php
 function getIp(){
   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;
 }
 echo 'The client\'s IP address is : '.getIp();
?>
Output:

The client's IP address is : 192.168.1.101

About Author:
V
Vinay Kumar     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.