# Help recording IP addresses using PHP! Need help ASAP.



## Trip (Dec 19, 2007)

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!


----------



## Captain Code (Dec 19, 2007)

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.


----------



## Trip (Dec 19, 2007)

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?


----------



## Captain Code (Dec 19, 2007)

OK, well you can give it a shot then and see how it performs.  The code is pretty simple; get IP address, open file, read line by line and compare.  If not found, append to end of file

I don't have much time to try and write the code myself but look at fopen and fgets
This is a good start http://www.devarticles.com/c/a/PHP/Working-With-Text-Files-in-PHP/1/


----------



## Trip (Dec 19, 2007)

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.


----------



## macbri (Dec 19, 2007)

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


```
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.


----------

