欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP 获取ip地址代码汇总

程序员文章站 2022-05-30 07:51:16
代码一: function getip() { static $ip = ''; $ip = $_server['remote_addr'];...

代码一:

function getip() {
  static $ip = '';
  $ip = $_server['remote_addr'];
  if(isset($_server['http_cdn_src_ip'])) {
    $ip = $_server['http_cdn_src_ip'];
  } elseif (isset($_server['http_client_ip']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_server['http_client_ip'])) {
    $ip = $_server['http_client_ip'];
  } elseif(isset($_server['http_x_forwarded_for']) and preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_server['http_x_forwarded_for'], $matches)) {
    foreach ($matches[0] as $xip) {
      if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
        $ip = $xip;
        break;
      }
    }
  }
  return $ip;
}

代码二:

<?php
error_reporting (e_error | e_warning | e_parse);
if($http_server_vars["http_x_forwarded_for"]){
$ip = $http_server_vars["http_x_forwarded_for"];
}
elseif($http_server_vars["http_client_ip"]){
$ip = $http_server_vars["http_client_ip"];
}
elseif ($http_server_vars["remote_addr"]){
$ip = $http_server_vars["remote_addr"];
}
elseif (getenv("http_x_forwarded_for")){
$ip = getenv("http_x_forwarded_for");
}
elseif (getenv("http_client_ip")){
$ip = getenv("http_client_ip");
}
elseif (getenv("remote_addr")){
$ip = getenv("remote_addr");
}
else{
$ip = "unknown";
}
echo $ip;
?>

方法三:

<?php
$iipp = $_server["remote_addr"];
echo $iipp ;
?>

方法四:

<?php
$user_ip = ($_server["http_via"]) ? $_server["http_x_forwarded_for"] : $_server["remote_addr"];
$user_ip = ($user_ip) ? $user_ip : $_server["remote_addr"];
echo $user_ip
?>

方法五:

<?php
function get_real_ip()
{
$ip=false;
if(!empty($_server["http_client_ip"])){
 $ip = $_server["http_client_ip"];
}
if (!empty($_server['http_x_forwarded_for'])){
 $ips = explode (", ", $_server['http_x_forwarded_for']);
 if($ip){
  array_unshift($ips, $ip); $ip = false;
 }
 for($i = 0; $i < count($ips); $i++){
  if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])){
  $ip = $ips[$i];
  break;
  }
 }
}
return($ip ? $ip : $_server['remote_addr']);
}
echo get_real_ip();
?>

方法六:

<?php
if(getenv('http_client_ip')){
$onlineip = getenv('http_client_ip');
}
elseif(getenv('http_x_forwarded_for')){
$onlineip = getenv('http_x_forwarded_for');
}
elseif(getenv('remote_addr')){
$onlineip = getenv('remote_addr');
}
else{
$onlineip = $http_server_vars['remote_addr'];
}
echo $onlineip;
?>

上一篇: 详解PHP中的PDO类

下一篇: 小时聪明