Gw Temp

Menu

Tutorial - 'IP Logging with PHP & MySQL' by skyrider

An item about Programming Languages posted on

Blurb

This tutorial shows you how to log IPs to a MySQL table with PHP.

Body

Have you ever wanted to log a visitors IP address for different reasons? There are MANY reasons why people want to log other's IP addresses such as to reporting them to their ISP if they were to spam your email from a form on yoru site. Continue reading if you want to learn more about logging IPs using PHP & MySQL.

-----Requirements-----
*Basic knowledge of MySQL (I will not be teaching you)
*Basic knowledge of PHP (I will not be teaching you)
*A webhost that supports PHP
*A MySQL database
--------------------------

First off, you need to connect to MySQL and select your database. The next thing you need to do is create a table called IP and in it, make a row called ip. Have it set as text.
Once you have sucessfully created your table, make a new file and call it logip.php. Inside of it, put in the following.


//connect to the database
include 'dbconnect.php';
//Is the users IP in the database?
$query = "SELECT * FROM IP";
$result = mysql_query($query) or die ("Error in query: $query.". mysql_error());
if (mysql_num_rows($result) < 0)
{
//If it isnt
//Get the visitors IP and store it in a vaiable
$ip = getenv("REMOTE_ADDR");
//Add visitors IP to the database
$query = "INSERT INTO IP(ip) VALUES('$ip')";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
}
//If it is
else {
}
?>

Now, it wouldnt be fair of me to not show you how I did this. So here we go.

//Is the users IP in the database?
$query = "SELECT * FROM IP";
$result = mysql_query($query) or die ("Error in query: $query.". mysql_error());
if (mysql_num_rows($result) < 0)

That does basically what the comment says it does. It checks to see if the users IP is already in the database.

Then we have some code inside brackets.

{
//If it isnt
//Get the visitors IP and store it in a vaiable
$ip = getenv("REMOTE_ADDR");
//Add visitors IP to the database
$query = "INSERT INTO IP(ip) VALUES('$ip')";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
}

That code inside the brackets will add the users IP to the database if it isnt already.

//If it is
else {
}

Then we have that last bit of code which means if the IP is already in the database, do nothing. (As you can see the empty space between the brackets)


Congratulations! You have now just made a fully working IP log script! But you may want to view the IP and not just have it sit in the database taking up space. But assuming that you know the basics of MySQL and PHP, that should be a breeze for you. I hope you learned a thing or two from this. Peace out.