使用PHP ip2long函数进行转换时,IP地址存储为0 [英] IP addresses get stored as 0 when converting with PHP ip2long function

查看:150
本文介绍了使用PHP ip2long函数进行转换时,IP地址存储为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL中的newsletter_ip字段设置为UNSIGNED INT(10)。我也尝试过INET_ATON来格式化数据,但我的结果总是看起来像这个

The newsletter_ip field in MySQL is set as an UNSIGNED INT (10). I've also tried INET_ATON to format the data, but my results always look like this.

以下是我的处理代码的一部分:

Here is part of my processing code:

//Retrieve data from user and create variables

$ip_orig = $_SERVER['REMOTE_ADDR'];

$ip = ip2long($ip_orig);

//Place into database

$sql = "INSERT INTO newsletter(newsletter_email, newsletter_ip, newsletter_date, newsletter_time) VALUES('".$email."', '".$ip."', '".$date."', '".$time."')";

我在ip2long格式化之前也试过这个片段,但无济于事:

I've also tried this snippet prior to the ip2long formatting, to no avail:

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

非常感谢任何帮助,谢谢!

Any help would be much appreciated, thanks!

推荐答案

找出问题的根本原因,ip2long提供了一个签名 int,如PHP手册所述:

for the root cause of your problem, ip2long gives a signed int as the PHP manual states:

注意:

因为PHP的整数类型是有符号的,并且许多IP地址会在32位体系结构上产生负整数,所以你需要使用sprintf()或printf()的%u格式化程序来获取未签名IP地址的字符串表示。

Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

并将其存储为 unsigned int ,这就是你看到ony零的原因。对于处理IPv6的标准和清洁解决方案,其他人已经提供了解决方案。

And you store it as an unsigned int, thats the reason why you see ony zeros. For a standard and clean solution handling IPv6 others have already given the solution.

这篇关于使用PHP ip2long函数进行转换时,IP地址存储为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆