How to get the IP address in PHP?

Many times we need to get the IP address of the visitor for different purposes. It is very easy to collect the IP address in PHP. PHP provides PHP $_SERVER variable to get the user IP address easily. We can track the activities of the visitor on the website for the security purpose, or we can know that who uses my website and many more.

The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.

Note
Note: We can display this IP address on the webpage and also even can store in database for many other purposes such as - for security, redirecting a visitor to another site, blocking/banning the visitor.

Get the IP address of the website

$_SERVER['REMOTE_ADDR'] - It returns the IP address of the user currently visiting the webpage.

For example

snippet
<?php
echo 'User IP Address - '.$_SERVER['REMOTE_ADDR'];
?>

Output

Output
User IP Address - ::1

But sometimes the REMOTE_ADDR does not return the IP address of the client, and the main reason behind is to use the proxy. In such type of situation, we will try another way to get the real IP address of the user in PHP.

snippet
<?php
	function getIPAddress() {
	//whether ip is from the share internet
   	 if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
        		$ip = $_SERVER['HTTP_CLIENT_IP'];
    	}
	//whether ip is from the proxy
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
   	 }
//whether ip is from the remote address
	else{
       		 $ip = $_SERVER['REMOTE_ADDR'];
   	 }
   	 return $ip;
}
$ip = getIPAddress();
echo 'User Real IP Address - '.$ip;
?>

Output

Output
User IP Address - ::1

Flowchart:

The flowchart for the above program will be like given below.

How to get the IP address in PHP

Get the IP address of the website

We can also get the IP address of any website by its URL. Pass the URL of the website inside gethostbyname() function.

For example

snippet
<?php
$ip_address = gethostbyname("www.google.com");
echo "IP Address of Google is - ".$ip_address;
echo "</br>";
$ip_address = gethostbyname("www.rookienerd.com");
echo "IP Address of rookienerd is - ".$ip_address;
?>

Output

Output
IP Address of Google is - 172.217.166.4 IP Address of rookienerd is - 95.216.57.234
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +