简体   繁体   English

使用PHP获取IP地址以正确显示

[英]Getting IP address with PHP to display correctly

I am trying to use the time and IP address to generate unique ID for users as they register for the site. 我正在尝试使用时间和IP地址为用户注册该站点生成唯一的ID。 The DB I'm using is MySQL and it comes with auto increment, but it doesn't seem like a practical technique for this. 我正在使用的数据库是MySQL ,它具有自动递增功能,但似乎并不实用。 I am having issues with $_SERVER['REMOTE_ADDR'] returning an unreadable address. $_SERVER['REMOTE_ADDR']返回无法读取的地址时出现问题。 I'm getting symbols for the value in the firebug console. 我正在萤火虫控制台中获取该值的符号。 I tried using inet_ntop and inet_pton , neither worked. 我尝试使用inet_ntopinet_pton ,都没有用。

$ip_address = $_SERVER['REMOTE_ADDR'];
$test = inet_ntop($ip_address);
echo($test);

Why am I getting symbols instead of readable text? 为什么我得到符号而不是可读的文本?

EDIT: 编辑:

What I want to store is a combination of the IP and time. 我要存储的是IP和时间的组合。 I need the IP to show in format of "79.104.97.105" -Niet the Dark Absol, but what I'm getting is if I use use inet_ntop or inet_pton or ::1 if I use just $_SERVER['REMOTE_ADDR']. 我需要IP以“ 79.104.97.105”的格式显示-Niet the Dark Absol,但是如果使用inet_ntop或inet_pton或,我得到的是 :: 1,如果我仅使用$ _SERVER ['REMOTE_ADDR']。

Two part question: 1) Am I getting the IP address as IPv6 if it returns ::1, 2) How do I convert to 127.0.0.1 which I think is IPv4 有两个部分的问题:1)如果IP地址返回:: 1,我是否将其获取为IPv6,2)我如何转换为我认为是IPv4的127.0.0.1

inet_ntop() expects the address in a binary format. inet_ntop()需要二进制格式的地址。

Example : 范例

$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

You need to use inet_pton() instead, which expects the IP in for format in $_SERVER['REMOTE_ADDR'] . 您需要使用inet_pton()代替,它要求IP以$_SERVER['REMOTE_ADDR']格式提供。

Update 更新

In the question you state that you need the address in readable format. 在问题中,您指出您需要可读格式的地址。

echo $_SERVER['REMOTE_ADDR'];

The variable already contains the IP in human readable format, no need for any PHP function to convert it. 该变量已经包含人类可读格式的IP,不需要任何PHP函数对其进行转换。

You can try this function : 您可以尝试以下功能:

function getRealIP(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

EDIT 编辑

This question may help you I think he had the same issue : Should a MAMP return ::1 as IP on localhost? 这个问题可能会对您有帮助,我认为他也有同样的问题: MAMP是否应将:: 1作为本地主机上的IP返回?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM