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.
$_SERVER['REMOTE_ADDR'] - It returns the IP address of the user currently visiting the webpage.
For example
<?php echo 'User IP Address - '.$_SERVER['REMOTE_ADDR']; ?>
Output
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.
<?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
Flowchart:
The flowchart for the above program will be like given below.
We can also get the IP address of any website by its URL. Pass the URL of the website inside gethostbyname() function.
For example
<?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