Monday, 13 August 2018

Get The IP Address Of A Visitor Through PHP

I have talked previously about getting an IP address of a visitor with PHP. The failing in using the value of $_SERVER['REMOTE_ADDR'] is that if the visitor is using a proxy then you will get the proxy IP address and not the visitors real IP address.
This function works by going through any variables in the $_SERVER array that might exist that would contain information to do with IP addresses. If they are all empty then the function finally looks at $_SERVER['REMOTE_ADDR'] value and returns this as a default.
  1. function getRealIpAddr(){
  2. if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
  3. // Check IP from internet.
  4. $ip = $_SERVER['HTTP_CLIENT_IP'];
  5. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
  6. // Check IP is passed from proxy.
  7. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  8. } else {
  9. // Get IP address from remote address.
  10. $ip = $_SERVER['REMOTE_ADDR'];
  11. }
  12. return $ip;
  13. }
To run this function just call it.
echo getRealIpAddr();

0 comments:

Post a Comment