如何在PHP中获取IP地址

时间:2012-08-08 12:00:00

标签: php apache

我在Windows 7操作系统上安装了Apache服务器2.2.22,Php 5.4.5和Mysql 5.5.27。每件事都很好。但我没有得到IP地址。这是我的IP地址收集代码

<?php

//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])) 
{
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    //Is it a proxy address
} 
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
{
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} 
else 
{
    $ip = $_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);

任何人都可以帮助我如何获得IP地址。我是否需要更改或修改Apache httpd.conf或php.ini文件以解决此问题。

2 个答案:

答案 0 :(得分:3)

获取用户IP地址的简单方法

<?PHP

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 177.87.193.134]


?>

答案 1 :(得分:2)

您可以使用$_SERVER['SERVER_ADDR']获取服务器IP,$_SERVER['REMOTE_ADDR']将返回用户正在查看的IP地址。