Want to log IP addresses that visit your site? Heres a simple solution using PHP.

Posted on March 4, 2010 by Scott in PHP

If you wish to have a simple ip-logger on your website, then a simple solution would to use PHP with two files. The first file you will need is the index.php file (or anyfile that you want logged) and put this code between the <body></body> tags:

<?php
     $logfile= ‘ip.html’;
     $IP = $_SERVER['REMOTE_ADDR'];
     $logdetails=  date(“F j, Y, g:i a O T”) . ‘: ‘ . ‘<a href=http://www.geobytes.com/IpLocator.htm?GetLocation&ipaddress=’.$_SERVER['REMOTE_ADDR'].’>’ .$_SERVER['REMOTE_ADDR'].’</a>’;
     $fp = fopen($logfile, “a”);  fwrite($fp, $logdetails);  fwrite($fp, “<br>”);
 fclose($fp);
 echo(“Your IP has been logged. It is $IP”);
?>

What this code does is write $logdetails to our second file $logfile = ‘ip.html’;. To access ip.html, just type the path in the address bar and you can look at all the IPs that have Visited!

I have not had to change any file permissions with this code, but you might have to change both file permissions with chmod 777. If your host runs a windows server, please contact your host support on how best to change file permissions as each host is different.

Further explaination:
  • Any word with $ character infront of it is a variable. We use several here with $logfile and $IP.
  • In $logfile = ‘ip.html’; the ‘ip.html’ means that everything between ” is a string. Sometimes it may mean just a character but here it shows ip.html is a string.
  • In $IP = $_SERVER['REMOTE_ADDR']; the variable $IP is being set to be the address of the computer visiting the website.
  • fopen($logfile, “a”); is our file handler. Without this we cant write to ip.html. “a” means we will be appending to the file, which means writing at the end of the file. No earlier logs will be erased.
  • fwrite($fp, $logdetails); writes to ip.html. $fp is the handle, $logdetails is the message we will write to ip.html.
  • fclose($fp); closes the file handle.
  • In $logdetais you will notice that there are functions as well as strings. To put the output of of the functon together with a string, just put between both of them ” . “. Yes use the spaces I have put in the quotes. remember to put ” or “” for your string! Functions do not need ” or “”.
  • The echo(); function prints out a message to your visitor letting them know the visit has been logged.

Tags: , ,

Comments (1)

 

  1. abcphp.com says:

    Want to log IP addresses that visit your site? Heres a simple solution using PHP. :Blehnesses…

    If you wish to have a simple ip-logger on your website, then a simple solution would to use PHP with two files. The first file you will need is the index.php file (or anyfile that you want logged) and put this code between the tags:…

Leave a Reply