Reputation: 77
I have a log file from which I am writing the data to a php file. This is the code for that:
$filename='/var/log/siawa/dashboard/iot.log';
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
$buffer = fgets($source_file, 4096); // use a buffer of 4KB
$buffer = str_replace($old,$new,$buffer);
echo $buffer. "<br />" . "\n";
}
This is working but i want to update the php log data after say every 10 seconds once its gets written in the original log file. How to do that.
Upvotes: 1
Views: 3667
Reputation: 18445
You need to read the file contents in an infinite while(true)
loop. I'll explain through code comments.
// read.php
<?php
// Last read position
$last = 0;
// Path to the updating log file
$file = 'log.txt';
while (true) {
// PHP caches file information in order to provide faster
// performance; In order to read the new filesize, we need
// to flush this cache.
clearstatcache(false, $file);
// Get the current size of file
$current = filesize($file);
// Reseted the file?
if ($current < $last) {
$last = $current;
}
// If there's new content in the file
elseif ($current > $last) {
// Open the file in read mode
$fp = fopen($file, 'r');
// Set the file position indicator to the last position
fseek($fp, $last);
// While not reached the end of the file
while (! feof($fp)) {
// Read a line and print
print fgets($fp);
}
// Store the current position of the file for the next pass
$last = ftell($fp);
// Close the file pointer
fclose($fp);
}
}
To test this, open a terminal window and issue:
while true; do echo `date` >> log.txt; sleep 1; done
This will append the current datetime string to the file for each single second. Now open another terminal and issue php read.php
to see if the file is being read in real-time. It will output something like this:
Wed Dec 28 18:01:12 IRST 2016
Wed Dec 28 18:01:13 IRST 2016
Wed Dec 28 18:01:14 IRST 2016
Wed Dec 28 18:01:15 IRST 2016
Wed Dec 28 18:01:16 IRST 2016
Wed Dec 28 18:01:17 IRST 2016
Wed Dec 28 18:01:18 IRST 2016
# Keeps updating...
If you tend to serve this over HTTP, you'll need to add a ob_flush()
call after printing the read buffer:
// While not reached the end of the file
while (! feof($fp)) {
print fgets($fp) . '<br>';
// Flush the output cache
ob_flush();
}
Upvotes: 3