Piggy
Piggy

Reputation: 67

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!

Upvotes: 1

Views: 2097

Answers (3)

JCH77
JCH77

Reputation: 1363

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}\r\n";
file_put_contents('/path/to/ips.log', $new_line, LOCK_EX | FILE_APPEND);

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

Upvotes: 1

mahdi ghasemi
mahdi ghasemi

Reputation: 67

$ip = getIPAddress();
$logFile = 'log.txt';
$log = file_get_contents($logFile);
$log .= "User Real IP Address - ".$ip."\n";
file_put_contents($log);

file_get_contents() reads entire file into a string ($log) then add more ip to it then write it again by file_put_contents().

Upvotes: 1

sukalogika
sukalogika

Reputation: 599

$ip = getIPAddress(); 

$handle = fopen("logs.txt","a");

$text = date("Y-m-d H:i:s")."\t".$ip;

fwrite($handle,$text);
fwrite($handle,PHP_EOL);

fclose($handle);

echo 'User Real IP Address - '.$ip;

Explaination:

  1. Get ip address.
  2. Open handle with append mode (fopen)
  3. Create text you want to log (at this time Date format dan IP address)
  4. Write that text with fwrite.
  5. Close handle created in step 2

Check your logs.txt

Upvotes: 1

Related Questions