PHP操作IP位址在mysql中的儲存方式

2021-06-02 17:02:49 字數 1121 閱讀 8866

php

echo ip2long('192.168.1.38');

輸出:3232235814

mysql

select inet_aton('192.168.1.38'); 

輸出:3232235814

兩個函式返回的結果是一樣的,都是a*256*256*256+b*256*256+c*256+d的演算法

192*256*256*256+168*256*256+1*256+38 = 3 232 235 814 

反過來,從int轉換為ip位址分別是php的long2ip()和mysql的inet_aton()。

mysql儲存這個值是字段需要用int unsigned。不用unsigned的話,128以上的ip段就儲存不了了。

傳統的方法,建立varchar(15),需要占用15個位元組,而改時使用int只需要4位元組,可以省一些位元組。

php存入時:$ip = ip2long($ip);

mysql取出時:select inet_aton(ip) from table ...

php取出時,多一步:$ip = long2ip($ip);

轉換以前的資料:

1.把以前的varchar()資料轉換為int型的sql語句:

update `hx_table` set ip =  inet_aton(ip) where inet_aton(ip) is not null 

2.把字段更改為int型:

alter table `hx_table` change `ip` `ip` int unsigned not null 

3.程式做相應修改上傳,完成。

@@update@@20110310:

在32位的機子上,echo ip2long('192.168.1.38');由於超過32位的最大數,導致輸出負數-1062731482。

有兩種方法更新為正數:

$ip_long = bindec(decbin(ip2long($ip)));

或$ip_long = = sprintf("%u", ip2long($ip));

因此一種是修改php程式,使其肯定存入正數。

另一種是將mysql的這個字段使用int,非unsigned,使其可以存入負數。

IP位址在mysql的儲存

因為int比varchar 15 更高效,且php和mysql都有ip和int互轉的函式,所以在ip位址在mysql中用int儲存最優。mysql儲存這個值是字段需要用int unsigned。不用unsigned的話,128以上的ip段就儲存不了了。echo ip2long 192.168.1.3...

PHP 獲取 ip 位址

remote addr 是你的客戶端跟你的伺服器 握手 時候的ip。如果使用了 匿名 remote addr將顯示 伺服器的ip。http client ip 是 伺服器傳送的http頭。如果是 超級匿名 則返回none值。同樣,remote addr也會被替換為這個 伺服器的ip。server r...

Mysql儲存IP位址

使用mysql函式 create table testip ip bigint 10 null insert into testip ip values inet aton 255.255.255.255 ip 4294967295 select inet ntoa ip ip from testi...