How to get IP addres in php function

PHP function for get user IP address. REMOTE_ADDR with PHP $_SERVER

How to use REMOTE_ADDR with $_SERVER?

Example with php


<?php
echo 'My IP - '.$_SERVER['REMOTE_ADDR'].'';  
?>

Output: My IP - 12.3.45.67

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(!emptyempty($_SERVER['HTTP_CLIENT_IP'])) {  
                $ip = $_SERVER['HTTP_CLIENT_IP'];  
        }  
    //whether ip is from the proxy  
    elseif (!emptyempty($_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 IP Address - '.$ip.'';  

?>

Output: User IP Address - 12.3.45.67

How to check website IP address?

PHP have gethostbyname() function for website IP address check. Try it:


<?php
echo 'My website server ip is '.gethostbyname("www.google.com").'';  
?>

Output: User IP Address - 216.58.208.196