Posted By

olemedia on 06/03/11


Tagged


Versions (?)

MySQL Store ip address


 / Published in: PHP
 

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

  1. //Test if it is a shared client
  2. if (!empty($_SERVER['HTTP_CLIENT_IP'])){
  3. $ip=$_SERVER['HTTP_CLIENT_IP'];
  4. //Is it a proxy address
  5. }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  6. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  7. }else{
  8. $ip=$_SERVER['REMOTE_ADDR'];
  9. }
  10.  
  11. //The value of $ip at this point would look something like: "192.0.34.166"
  12. //Below the $ip would now look something like: 1073732954
  13. $ip = ip2long($ip);
  14.  
  15. // 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:
  16. $sql = "INSERT INTO user(ip) VALUES('$ip')";
  17. $dbQuery = mysql_query($sql,$dbLink);
  18.  
  19. // To retrieve the original IP address from the database you can use the mysql function INET_NTOA like so:
  20. SELECT INET_NTOA(ip) FROM 'user' WHERE 1
  21.  
  22. //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.

Report this snippet  

You need to login to post a comment.