Save IP in database

2019-04-13 23:00发布

When a user logs in I want to save their IP in the database. How would I do that? What type is best to use for the MySQL field? How would the PHP code to get IP look like?

I'm thinking of using it as an extra security feature for the login/session stuff. I'm thinking of checking the IP the user logged in with from the DB with the IP the user have now as addition to checking the session. So that it first check the session, and then check if you have a valid IP.

Is that a good extra feature? And what other things can I do to make it more secure?

标签: php mysql ip
3条回答
甜甜的少女心
2楼-- · 2019-04-13 23:02

as Lauri Lehtinen said,you use the $_SERVER['REMOTE_ADDR'] to get the IP-Address, for a simple PHP Code look below ...

<?php
$conn = mysql_connect("server","username","password");//server, username and password are your server address and access details
if(!$conn)
    die("cannot connect to mysql server" . mysql_error());
mysql_select_db("database Name", $conn);
$sql = "INSERT INTO table_name (IP_Address) VALUES(" . $_SERVER['REMOTE_ADDR'] . ")";
if(!mysql_query($sql,$conn))
    die("ERROR: " .mysql_error());
mysql_close($con);
?>

This is just a sample just modify it to suite your needs ...

查看更多
倾城 Initia
3楼-- · 2019-04-13 23:12

Have a look at the INET_NTOA and INET_ATON functions in mysql. They convert between dotted notation IP address to 32 bit integers. This allows you to store the IP in just 4 bytes rather than a 15 bytes. Make sure you use an unsigned int and not a signed int.

查看更多
Rolldiameter
4楼-- · 2019-04-13 23:14

In regards to William Leader's suggestion, PHP has two functions ip2long and long2ip that do exactly what he's talking about.

查看更多
登录 后发表回答