Home >>PHP Programs >How to get IP address in PHP

How to get IP address in PHP

How to get IP address in PHP

Before finding any IP address, let's understand what IP address is. IP address basically translates to the Internet protocol IP address and it is a numerical label assigned to each device that is connected to a computer network and uses the internet protocol in order to communicate. This IP address needed to be tracked various times that are of the users or visitors for various purposes. Since, PHP delivers PHP $_SERVER variable that is used to get the user IP address, now it is extremely easy to get the IP address in PHP. The main use of the IP address tracking is in knowing that what a visitor is doing on your website and who is the user that is using your website, there are numerous reasons for it but the main reason is security.

In this article you will learn about finding the IP address in PHP. The simplest way of gathering the visitor IP address in PHP is to use the REMOTE_ADDR. In order to use the ‘REMOTE_ADDR' in PHP you have to pass it in the $_SERVER variable, it will return the IP address of the visitor that is browsing the webpage at the current tikme.

Note :The IP address that has been tracked can be either stored in a database or displayed on the webpage for various other purposes like for security, redirecting a visitor to another site, blocking/banning the visitor.

Get the Visitors(Users) IP Address

$_SERVER['REMOTE_ADDR'] – This function generally returns the IP address of the user that is visiting the webpage at the current time.

Here is an example:

<?php  
$ip_Address = $_SERVER['REMOTE_ADDR'];  
echo "Here is the IP Address of Visitors : ".$ip_Address;  
?>
Output :
Here is the IP Address of Visitors : ::1

Note :The IP address of Local System(localhost) 127.0.0.1

Get the IP address of the website

The IP address of the visitor can also be obtained from the URL of any website. All you have to do is to just pass the URL of the website inside the function that is name: gethostbyname()

Here is an example:

<?php  
$GoogleipAddress = gethostbyname("www.google.com");  
echo "Here is the IP Address of Google : ".$GoogleipAddress;  
echo "</br>";  

$Fbip_address = gethostbyname("www.facebook.com");  
echo "Here is the IP Address of facebook : ".$Fbip_address;  
?>
Output :
Here is the IP Address of Google : 172.217.160.228
Here is the IP Address of facebook : 103.211.217.36

No Sidebar ads