1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Logging IP Addresses w/o Duplicates

Discussion in 'PHP' started by Hyphen, Dec 22, 2008.

  1. #1
    <?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?
     
    Hyphen, Dec 22, 2008 IP
  2. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #2
    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
     
    crivion, Dec 22, 2008 IP
  3. PwrUps

    PwrUps Peon

    Messages:
    377
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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):
     
    PwrUps, Dec 22, 2008 IP
  4. PwrUps

    PwrUps Peon

    Messages:
    377
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    PwrUps, Dec 22, 2008 IP
  5. powerspike

    powerspike Peon

    Messages:
    312
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #5
    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.
     
    powerspike, Dec 22, 2008 IP