In this tutorial you can learn How to create logs and display them in your webpage. By logs we mean number of views etc.

Consider this code

Let it be named as "track.php"

<?php
// Getting the information
$ipaddress = $_SERVER["REMOTE_ADDR"];
$datetime = time();
$useragent = $_SERVER["HTTP_USER_AGENT"];
$remotehost = @getHostByAddr($ipaddress);

// Create log line
$logline = $ipaddress . "|" . $datetime . "|" . $useragent . "|" . $remotehost . PHP_EOL;

// Write to log file:
$logfile = "logfile.txt";

// Open the log file in "Append" mode
if (!$handle = fopen($logfile, "a+")) {
die("Failed to open log file");
}

// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
die("Failed to write to log file");
}

fclose($handle);

// Open log file
$logfile = "logfile.txt";

if (file_exists($logfile)) {

$handle = fopen($logfile, "r");
$log = fread($handle, filesize($logfile));
fclose($handle);
} else {
die ("The log file does not exist!");
}

// Seperate each logline
$log = explode("\n", trim($log));

// Seperate each part in each logline
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode("|", $log[$i]);
}


?>
In this file, the method of creating logs and saving them in a text-file on your local system is coded. First we gathered some information, then created a log, opened the textfile in append mode and appended that log into that text-file.



Now, consider this code

Let it be named as "index.php"

<?php
include("track.php");
date_default_timezone_set("Asia/Kolkata");

echo "<b style="font-size:40px;">".count($log)." views on this website."."</b>";

echo "<table border="1">";
echo "<th>IP Address</th>";
echo "<th>Date</th>";
echo "<th>User Agent</th>";
echo "<th>Remote Host</th>";

foreach ($log as $logline) {
echo "<tr>";

echo "<td>" . $logline["0"] . "</td>";
echo "<td>" . date("d-m-Y h:i:sa", $logline["1"]) . "</td>";
echo "<td>" . $logline["2"] . "</td>";
echo "<td>" . $logline["3"] . "</td>";

echo "</tr>";

}
?>

This page will be used to display the logs on the website using track.php file and text-file of logs that is present on the local system.