问题
I'm using PHP and MySQL, and I want to store users' IP addresses into the database for comparison purposes (e.g. allowing only one flag to a thread per IP). Would it be okay to do it the following way?
Retrieving it in PHP:
$ipAddress = md5($_SERVER["REMOTE_ADDR"]);
And then saving it into the database as a VARCHAR(32)
.
If I had to make a more comprehensive use of the IPs this wouldn't be the proper way to do it I guess, but if it's only to make sure that the same IP didn't do something twice would be okay to use the md5 encryption to simplify things (unifying IPv4 and IPv6 addresses into one)?
回答1:
Yes, this is fine, though your terminology is wrong: this is hashing, and hashing is not encryption.
You should also parse the X-FORWARDED-FOR
and Client-IP
headers unless you want to block everyone behind a proxy as if they were a single user (e.g. everyone at large companies, high schools, etc).
回答2:
You might want to consider converting the IP to a number. A little quicker on the lookup because it's numeric data and you can use INET_ATON() and INET_NTOA() in your queries.
http://dev.mysql.com/doc/refman/5.5/en/miscellaneous-functions.html#function_inet-aton
mysql> SELECT INET_ATON('10.0.5.9');
-> 167773449
http://dev.mysql.com/doc/refman/5.5/en/miscellaneous-functions.html#function_inet-ntoa
mysql> SELECT INET_NTOA(167773449);
-> '10.0.5.9'
PHP to Convert to a number
$ipA = $_SERVER["REMOTE_ADDR"];
$octets = split ("\.", $ipA);
$ipN = ($octets[3] + $octets[2] * 256 + $octets[1] * pow(256,2) + $octets[0] * pow(256,3);
Also, you might want to consider the IP Address you're using with this function:
/* Get Actual IP Address, in spite of proxy server */
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{ $ip=$_SERVER['HTTP_CLIENT_IP']; }
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{ $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; }
else
{ $ip=$_SERVER['REMOTE_ADDR']; }
return $ip;
}
RE-Edit for IPv6:
Principles all still apply, but IPv6 Conversions already answered at How to convert IPv6 from binary for storage in MySQL
来源:https://stackoverflow.com/questions/10369783/encrypting-users-ip-address-before-storing-it