Home  >  Article  >  Backend Development  >  PHP function to obtain online IP and client IP

PHP function to obtain online IP and client IP

WBOY
WBOYOriginal
2016-07-25 08:54:031300browse
  1. /**

  2. * Get client ip
  3. * @return [string] [description]
  4. */
  5. function getclientip() {
  6. $ip = null;
  7. if (isset($_server['http_x_forwarded_for'])) {
  8. $arr = explode(',', $_server['http_x_forwarded_for']);
  9. $pos = array_search('unknown',$arr);
  10. if(false !== $pos) unset($arr[$pos]);
  11. $ip = trim($arr[0]);
  12. }elseif (isset($_server['http_client_ip'])) {
  13. $ip = $_server['http_client_ip'];
  14. }elseif (isset($_server['remote_addr'])) {
  15. $ip = $_server['remote_addr'];
  16. }
  17. // ip地址合法验证
  18. $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
  19. return $ip;
  20. }

  21. /**

  22. * Get online ip
  23. * @return string
  24. */
  25. function getonlineip($format=0) {
  26. global $s_global;
  27. if(empty($s_global['onlineip'])) {
  28. if(getenv('http_client_ip') && strcasecmp(getenv('http_client_ip'), 'unknown')) {
  29. $onlineip = getenv('http_client_ip');
  30. } elseif(getenv('http_x_forwarded_for') && strcasecmp(getenv('http_x_forwarded_for'), 'unknown')) {
  31. $onlineip = getenv('http_x_forwarded_for');
  32. } elseif(getenv('remote_addr') && strcasecmp(getenv('remote_addr'), 'unknown')) {
  33. $onlineip = getenv('remote_addr');
  34. } elseif(isset($_server['remote_addr']) && $_server['remote_addr'] && strcasecmp($_server['remote_addr'], 'unknown')) {
  35. $onlineip = $_server['remote_addr'];
  36. }
  37. preg_match("/[d.]{7,15}/", $onlineip, $onlineipmatches);
  38. $s_global['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
  39. }

  40. if($format) {

  41. $ips = explode('.', $s_global['onlineip']);
  42. for($i=0;$i<3;$i++) {
  43. $ips[$i] = intval($ips[$i]);
  44. }
  45. return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
  46. } else {
  47. return $s_global['onlineip'];
  48. }
  49. }

复制代码

php获取远程客户端真实ip地址 php在内网机器获取公网IP的方法 php读取纯真ip数据库的简单例子 PHP获取本机的局域网IP地址方法 PHP获取局域网中计算机名、IP地址与MAC地址 PHP获取IP地址的多种方法 PHP通过IP获取地理位置的代码 PHP获取指定的IP网段信息 php IP获取城市API(纯真IP数据库) php获取真实ip地址的实例分享 探讨:PHP获取域名及域名IP地址的方法 php通过IP获取地理位置的实例参考



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn