<?php $ip = $_SERVER['REMOTE_ADDR']; $file = fopen("log.txt", "a"); fwrite($file, 'IP: '.$ip.'); fclose($file); ?> Code (markup): A very simple code, but how can I make this not record duplicate IP entries? Also, if I was trying to make this record IPs referred only from a certain domain, how can I do that?
I would use preg_match in this case but the best solution is to use a mysql db with a table to store ip's and checking when adding a new entry for existing ip before
You can read the content and use strpos (http://us2.php.net/strpos) or preg_match (http://us3.php.net/manual/en/function.preg-match.php) to find out whether or not an IP exists in the file. With strpos: $content = fread($file, filesize("log.txt")); if (strpos($content, $ip) === false) { fwrite($file, 'IP: '.$ip.'); } else { echo "There was an IP match."; } Code (markup): With preg_match: $content = fread($file, filesize("log.txt")); if (preg_match("/{$ip}/", $content) == 0) { fwrite($file, 'IP: '.$ip.'); } else { echo "There was an IP match."; } Code (markup):
Use the $_SERVER['HTTP_REFERER'] variable in addition to check for a certain domain. (http://us.php.net/manual/en/reserved.variables.server.php)
personally, i'd just log the IP addresses into the database, and make sure the IP address field is set to unquie, it's nasty and quick, but would work.