Get real IP address in PHP

June 26th, 2012 by laeeq | 1 comment

Most of us use $_SERVER['REMOTE_ADDR'] to find the client’s IP address in PHP. But you should know that it may not return the true IP address of the client at all time. Suppose if your client is connected to the Internet through Proxy Server then $_SERVER['REMOTE_ADDR'] in PHP just returns the IP address of the proxy server not of the client’s machine. So here is a simple function to find the real IP address of the client’s machine. Actually there are few Server variable (HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR) that return exact IP address of the client’s machine in PHP.

Use below mentioned function to find real IP address in PHP

  1. function getRealIpAddress()
  2. {
  3. if (!empty($_SERVER['HTTP_CLIENT_IP']))
  4. {
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];
  6. }
  7. elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
  8. {
  9. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  10. }
  11. else
  12. {
  13. $ip=$_SERVER['REMOTE_ADDR'];
  14. }
  15. return $ip;
  16. }

In above PHP function, I have used $_SERVER['HTTP_CLIENT_IP'] server variable to get the direct IP address of client’s machine, if IP address of client’s machine not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. if IP address using HTTP_X_FORWARDED_FOR not available, then finally try to get the IP address using REMOTE_ADDR.

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

 

 

  1. philgarciang
    September 28th, 2012 at 11:55 | #1

    Enjoyed reading through this, very good stuff, thankyou . “Love begets love, love knows no rules, this is the same for all.” by Virgil.

  1. No trackbacks yet.