Best way to store IP addresses in MySQL
You’ll realise I’m sure that you can’t just add the dotted IP address straight into an INT field without first converting it into a valid format. For that you’ll need a PHP function called which will convert a string containing an IP dotted address into a integer that can be stored in the INT field.
Here is a quick example of how you might go about getting the real IP address of a client and then storing and retrieving its value from the mysql DB:
1
2
3
4
5
6
7
8
9
10
11
12
| //Test if it is a shared clientif (!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);//The $ip would now look something like: 1073732954 |
1
2
| $sql = "INSERT INTO user(ip) VALUES('$ip')";$dbQuery = mysql_query($sql,$dbLink); |
1
| SELECT INET_NTOA(ip) FROM 'user' WHERE 1 |
Storing IP addresses in this manner is beneficial because it takes less space than storing it as a string. The other benefit is that lookups are faster because integer comparisons are quicker than string comparisons.
No comments:
Post a Comment