Return to Snippet

Revision: 47225
at June 3, 2011 00:08 by olemedia


Initial Code
//Test if it is a shared client
if (!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"
//Below the $ip would now look something like: 1073732954
$ip = ip2long($ip);

// Now that you have the real IP address of the client converted to the INT format, you can write it into the DB as you normally would:
$sql = "INSERT INTO user(ip) VALUES('$ip')";
$dbQuery = mysql_query($sql,$dbLink);

// To retrieve the original IP address from the database you can use the mysql function INET_NTOA like so:
SELECT INET_NTOA(ip) FROM 'user' WHERE 1

//Alternately you could use the PHP function longtoip to convert the returned INT value into the dotted IPv4 address in the PHP code instead, and you could even add the dotted IP address to the INT field in the db using the mysql funtion INET_ATON.

Initial URL
http://daipratt.co.uk/mysql-store-ip-address/

Initial Description


Initial Title
MySQL Store ip address

Initial Tags


Initial Language
PHP