View Full Version : Saving IP address in database.

The reaper
06-17-2010, 06:29 AM
Hello there,

what I have been searching for on google, here, and daniweb is a way to save the registration form submitter's IP address. This is to prevent spamming of accounts. Here is the registration form itself.

<?php include("tophead.php"); ?>
<?php include("header.php"); ?>
<form name="registration_form" method="post" action="register.php">
Username: <input type="text" name="username"><br />
Password: <input type="password" name="password"><br />
Email: <input type="text" name="email">(Enter only if you want to receive news/deals/and other stuff)<br />
<input id="ip" name="ip" value='<?php echo $_server["remote_address"]; ?>' type='hidden'>
<input type="submit" value="Submit">

Here is register.php

$to = "*****";
$subject = "New Member";
$body = "A new member has joined.";
if (mail($to, $subject, $body)) {
echo("<p>Thank you for joining! You may now login!</p>");
} else {
echo("<p>A problem has occur, please try again.</p>");
mysql_select_db("****",$connect) or
die (mysql_errno().":<b> ".mysql_error()."</b>");
$insert_query = 'insert into user (


"' . $_POST['username'] . '",
"' . md5($_POST['password']) . '",
"' . $_POST['email'] . '",
"' . $_POST['ip'] . '"

<meta http-equiv="refresh" content="3;url=index.php"/>

In the MySQL db, "ip" is saved as int(20).

Thanks for the info!

06-17-2010, 07:52 AM
An IP address isn't a number, its a string due to the decimal points. Change your database field that stores the IP address to varchar(15) instead.

Also, the correct PHP code to get someone's IP address is:


You have "remote_address".

I also suggest not making the IP a hidden field in your form, but get the value of it after the form is submitted.

If you need anymore help I'll be glad to assist. :)

Edit: you want to use mysql_real_escape_string() (http://www.php.net/mysql_real_escape_string) on the variables that are in your query to help prevent sql injection too :)

The reaper
06-18-2010, 01:37 AM
thank you very much! I am going to change remote part and read more about prevention injections.

06-18-2010, 04:57 AM
There are numerous benefits gained when storing IPs as integers:

The reaper
06-18-2010, 05:45 AM
Ok, so now I am confused...do I save it as varchar or int? Which has the better benefits to use?