Log in

View Full Version : Creating a log



lankinator
04-08-2007, 05:34 PM
How would you create a .log file (that includes time + date + IP) for every time someone visit a page?

mburt
04-08-2007, 05:37 PM
$handle = fopen("includes/myfile.log","w+");
$time = date("d-m-Y");
$ip = $_SERVER["REMOTE_ADDR"];
$data = $time." -- IP: ".$ip;
fwrite($handle,$data);
fclose($handle);

lankinator
04-08-2007, 05:39 PM
thanks :d

lankinator
04-08-2007, 05:44 PM
how would i make it say what page they where looking at?

mburt
04-08-2007, 05:52 PM
Add this to the query:

$_SERVER["PHP_SELF"]

lankinator
04-08-2007, 05:52 PM
thanks :D

lankinator
04-08-2007, 05:54 PM
so would it be:

<?
$handle = fopen("zineviews.html","w+");
$time = date("d-m-Y");
$ip = $_SERVER["REMOTE_ADDR"];
$data = "DATE: ".$time."<br>IP: ".$ip. .$_SERVER["PHP_SELF"]"<br>-------------------</br><br>";
fwrite($handle,$data);
fclose($handle);
?>

mburt
04-08-2007, 06:00 PM
<?
$handle = fopen("zineviews.html","w+");
$time = date("d-m-Y");
$ip = $_SERVER["REMOTE_ADDR"];
$data = "DATE: ".$time."<br>IP: ".$ip .$_SERVER["PHP_SELF"]."<br>-------------------</br><br>";
fwrite($handle,$data);
fclose($handle);
?>
You had some of your dots in the wrong place, everything else is fine.

Note that this script will erase the log everytime, so use this:

<?
$handle = fopen("zineviews.html","w+");
$time = date("d-m-Y");
$ip = $_SERVER["REMOTE_ADDR"];
$data = file_get_contents("zineviews.html") . "DATE: ".$time."<br>IP: ".$ip .$_SERVER["PHP_SELF"]."<br>-------------------</br><br>";
fwrite($handle,$data);
fclose($handle);
?>

Twey
04-08-2007, 06:25 PM
Don't read the whole thing into memory and then write it back... the underlying OS supplies an append ability for files, which would be much more efficient (especially if you end up with gigabyte log files... bye-bye, server's memory!). Also, HTML's kind of tricky here, because you have to insert the data before the ending </body> and </html> tags, rather than simply appending. It would be easier to use a plain text file. Also, if you use PHP_SELF, it will break if used as an include (which is the best way to use it). Try REQUEST_URI instead -- that will give a better overview of what was requested, too, and will include GET variables.
<?php
$f = fopen('zineviews.txt', 'a');
$entry = <<< END
Log entry, &#37;s:
A view of %s occurred from IP %s.

END;
$entry = sprintf($entry, date('r'), $_SERVER['HTTP_REQUEST_URI'], $_SERVER['HTTP_REMOTE_ADDR']);
fwrite($f, $entry);
fclose($f);
?>

mburt
04-08-2007, 06:34 PM
Woah... you've completely lost me there. I understand the whole re-reading the file bit, but the <<< END thing? What's that?

Twey
04-08-2007, 06:46 PM
That's here-document syntax (http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc).