Help recording IP addresses using PHP! Need help ASAP.

Trip

Registered
Hello,

I'm trying to do something really simple, but I'm having trouble figuring out how to do it.

Basically I'm trying to get the IP address of a user who visits a PHP page using "getenv("REMOTE_ADDR")" and then having the script record that IP into a text file. But I also want the same PHP script to first check the text file to see if the IP is already in it.

Make sense?

It should be simple, but because I have no real in-depth knowledge of PHP I can't figure out how to get it done. Help!
 
Do you have access to a database? Doing that is going to start out fast but quickly become very slow checking all those lines in the text file. With a database you can have your IP address field indexed and it'll be very fast to check against existing entries this way.
 
Thanks for the reply Captain Code, I was thinking about using a database for this, but it was decided against. So I'm trying to find a way to do it just using a text file - despite the fact it will run slower with a lot of information.

Can you still help me?
 
Thanks for the help Captain Code, I really appreciate it!

If anybody else can help me put this all together that would be great as well.
 
The documentation at php.net is very good. I think you'd learn a lot more by trying to write this yourself.

Having said that, the below might steer you in the right direction

Code:
function addUnique($ip) {
    $file = fopen("ip.txt", "r+");
    $found = FALSE;                      
    while (! feof($file) && ! $found) {
        $line = trim(fgets($file));
        if ($line == $ip) $found = TRUE;
    }
    if (! $match) {
        /* Write results here */
    }
    fclose($file);
}

You're 80% of the way there. All you need to figure out is how to seek to the end of the file and how to write the IP address to it. Things you might consider while working on this:

  • In the fopen() call, is the "r+" mode important, and if so, why?
  • What does feof() do?
  • What does trim() do and why is it used here?

If this seems like an obtuse answer, it is. "Give a man a fish" and all that. :D
 
Back
Top