Posted By

Ideandro on 03/02/11


Tagged

php ip address


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Ideandro


GetIPaddress


 / Published in: PHP
 

URL: http://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php

  1. function GetIPaddress()
  2. {
  3. foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
  4. {
  5. if (array_key_exists($key, $_SERVER) === true)
  6. {
  7. foreach (explode(',', $_SERVER[$key]) as $ip)
  8. {
  9. $ip = trim($ip); // just to be safe
  10.  
  11. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 || FILTER_FLAG_IPV6 || FILTER_FLAG_NO_PRIV_RANGE || FILTER_FLAG_NO_RES_RANGE) !== false)
  12. {
  13. return $ip;
  14. }
  15. }
  16. }
  17. }
  18. }

Report this snippet  

You need to login to post a comment.