Skip to content
Advertisement

How do I Save IP’s of Those Who Visit My Website to logs.txt?

I have a website with which I want to record the ip’s of those who visit it. Now, I think I have some code that will do the job (I got this from here):

<?php  
    function getIPAddress() {  
    //whether ip is from the share internet  
     if(!emptyempty($_SERVER['HTTP_CLIENT_IP'])) {  
                $ip = $_SERVER['HTTP_CLIENT_IP'];  
        }  
    //whether ip is from the proxy  
    elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
     }  
//whether ip is from the remote address  
    else{  
             $ip = $_SERVER['REMOTE_ADDR'];  
     }  
     return $ip;  
}  
$ip = getIPAddress();  
echo 'User Real IP Address - '.$ip;  
?>  

What I want this to end up doing is saving the ip address and the date of everyone who visits my website to a log.txt file. I think that you use the fwrite command to do this, but I really have no idea. I don’t know anything about php, so I am looking for a book (any recommendations would be well appreciated). There are a lot of seemingly outdated or straight up wrong tutorials for php out there and I would love to avoid those.

Any help appreciated!

Advertisement

Answer

You can do it with file_put_contents(). Don’t forget to use a lock to avoid data loss.

$ip = getIpAdress();
$now = date('c');
$new_line = "{$now} {$ip}rn";
file_put_contents('/path/to/ips.log', $new_line, LOCK_EX | FILE_APPEND);

https://php.net/file-put-contents

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement