• Register

How to find the user IP address that visiting the page using PHP?

1 like 0 dislike
8,397 views
How to find visitor IP address of website using PHP to log each visit?
asked Apr 26, 2016 by anonymous

1 Answer

1 like 0 dislike
 
Best answer
PHP $_SERVERDescription
$_SERVER['REMOTE_ADDR']Most reliable way to get client IP address in PHP
$_SERVER'[HTTP_CLIENT_IP']This when user is behind proxy
$_SERVER['HTTP_X_FORWARDED_FOR']This when user is behind proxy
$_SERVER['HTTP_X_FORWARDED']This when user is behind proxy
$_SERVER['HTTP_FORWARDED_FOR'This when user is behind proxy
$_SERVER['HTTP_FORWARDED']This when user is behind proxy
$_SERVER['HTTP_X_CLUSTER_CLIENT_IP']This when user is behind proxy

 

<?php
echo GetClientIP(true);

function 
GetClientIP($validate False){
  
$ipkeys = array(
  
'REMOTE_ADDR'
  
'HTTP_CLIENT_IP'
  
'HTTP_X_FORWARDED_FOR'
  
'HTTP_X_FORWARDED'
  
'HTTP_FORWARDED_FOR'
  
'HTTP_FORWARDED'
  
'HTTP_X_CLUSTER_CLIENT_IP'
  
);
  
  
/*
  now we check each key against $_SERVER if contain such value
  */
  
$ip = array();
  foreach(
$ipkeys as $keyword){
    if( isset(
$_SERVER[$keyword]) ){
      if(
$validate){
        if( 
ValidatePublicIP($_SERVER[$keyword]) ){
          
$ip[] = $_SERVER[$keyword];
        }
      }else{
        
$ip[] = $_SERVER[$keyword];
      }
    }
  }
  
  
$ip = ( empty($ip) ? 'Unknown' implode(", "$ip) );
  return 
$ip;
  
}
function 
ValidatePublicIP($ip){
  if(
filter_var($ipFILTER_VALIDATE_IPFILTER_FLAG_NO_PRIV_RANGE FILTER_FLAG_NO_RES_RANGE)) {
    return 
true;
  }
  else {
    return 
false;
  }
}


?>

answered Apr 26, 2016 by anonymous
selected Aug 2, 2016 by learnipaddress
Please check our IP Tools - This Project sponsored by STANDING Tech Company
...