Home >Backend Development >PHP Tutorial >Four ways to get the client IP address in php

Four ways to get the client IP address in php

WBOY
WBOYOriginal
2016-07-25 09:03:511140browse
  1. $iipp=$_SERVER["REMOTE_ADDR"];
  2. echo $iipp;
  3. ?>
复制代码

第二种方法:

  1. $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];

  2. $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];

  3. echo $user_IP;

  4. ?>

复制代码

  1. function get_real_ip(){
  2. $ip=false;
  3. if(!empty($_SERVER["HTTP_CLIENT_IP"])){
  4. $ip = $_SERVER["HTTP_CLIENT_IP"];
  5. }
  6. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  7. $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
  8. if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
  9. for ($i = 0; $i < count($ips); $i++) {
  10. if (!eregi ("^(10|172.16|192.168).", $ips[$i])) {
  11. $ip = $ips[$i];
  12. break;
  13. }
  14. }
  15. }
  16. return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
  17. }

  18. echo get_real_ip();

  19. ?>

复制代码

第三处方法:

  1. //php获取ip的算法
  2. if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
  3. {
  4. $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  5. }
  6. elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
  7. {
  8. $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
  9. }
  10. elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
  11. {
  12. $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
  13. }
  14. elseif (getenv("HTTP_X_FORWARDED_FOR"))
  15. {
  16. $ip = getenv("HTTP_X_FORWARDED_FOR");
  17. }
  18. elseif (getenv("HTTP_CLIENT_IP"))
  19. {
  20. $ip = getenv("HTTP_CLIENT_IP");
  21. }
  22. elseif (getenv("REMOTE_ADDR"))
  23. {
  24. $ip = getenv("REMOTE_ADDR");
  25. }
  26. else
  27. {
  28. $ip = "Unknown";
  29. }
  30. echo "你的IP:".$ip ;
  31. ?>
复制代码

第四种方法:

  1. if(getenv('HTTP_CLIENT_IP')) {
  2. $onlineip = getenv('HTTP_CLIENT_IP');
  3. } elseif(getenv('HTTP_X_FORWARDED_FOR')) {
  4. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  5. } elseif(getenv('REMOTE_ADDR')) {
  6. $onlineip = getenv('REMOTE_ADDR');
  7. } else {
  8. $onlineip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
  9. }
  10. echo $onlineip;
  11. ?>
复制代码


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