php获取访问者IP地址汇总

在很我的时候我们需要得到用户的真实IP地址,例如,日志记录,地理定位,将用户信息,网站数据分析等,其实获取IP地址很简单$_SERVER[\'REMOTE_ADDR\']就可以了。下面我们就来给大家汇总一下常用的几种获取IP地址的方法。

方法1:

$ip = $_SERVER["REMOTE_ADDR"];

echo $ip;

方法2:

  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;

方法3:

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

方法4:

  1. if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
  2. {
  3. $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  4. }
  5. elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
  6. {
  7. $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
  8. }
  9. elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
  10. {
  11. $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
  12. }
  13. elseif (getenv("HTTP_X_FORWARDED_FOR"))
  14. {
  15. $ip = getenv("HTTP_X_FORWARDED_FOR");
  16. }
  17. elseif (getenv("HTTP_CLIENT_IP"))
  18. {
  19. $ip = getenv("HTTP_CLIENT_IP");
  20. }
  21. elseif (getenv("REMOTE_ADDR"))
  22. {
  23. $ip = getenv("REMOTE_ADDR");
  24. }
  25. else
  26. {
  27. $ip = "Unknown";
  28. }
  29. echo $ip ;

方法5:

  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;

方法6:

  1. print "您的IP地址是:";
  2. if(!emptyempty($_SERVER["HTTP_CLIENT_IP"])){
  3. $cip = $_SERVER["HTTP_CLIENT_IP"];
  4. }
  5. elseif(!emptyempty($_SERVER["HTTP_X_FORWARDED_FOR"])){
  6. $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  7. }
  8. elseif(!emptyempty($_SERVER["REMOTE_ADDR"])){
  9. $cip = $_SERVER["REMOTE_ADDR"];
  10. }
  11. else{
  12. $cip = "无法获取!";
  13. }
  14. print $cip;