I am using PHP to read in a .txt file, and parsing the data to a webpage. The .txt file is a local log file that displays my server’s status, and I can currently read out the last line and push it out to my site.
However, when my server’s status changes, the .txt file becomes updated locally, but the new value never shows up on the site.
I am using HTML5/Javascript for displaying the contents, and PHP for reading the file and parsing/cleaning up the input. The code segment I am attaching, which shows the PHP file reading functions I am using, runs every 10 seconds. After this segment is run, the display (I am using an HTML5 canvas) is refreshed, but the data stays constant. The display only updates if I manually refresh the page.
Is it possible that to poll this txt file every 10 seconds or so, and push the last line out into a variable I can call?
function getCurrentStatus() {
<?php
clearstatcache();
$myFile = "C:\available.log";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
$statusList = explode("\n", $theData);
$statusListLength = count($statusList) - 2;
$currentStatus = explode(" ", $statusList[$statusListLength]);
$previousStatus = explode(" ", $statusList[$statusListLength - 1]);
$myFile = "C:\std_server0.out";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
$garbageCollector = array_map('trim',explode("\n", $theData));
$garbageCollectorLength = count($garbageCollector);
?>
currentStatus = ["Latest Status:", "<?php echo $currentStatus[0]; ?>", "First Started:", "<?php echo $currentStatus[1]; ?>", "<?php echo $currentStatus[2]; ?>", "Last Checked:", "<?php echo $currentStatus[4]; ?>", "<?php echo $currentStatus[5]; ?>"];
latestGC = "<?php echo $garbageCollector[$garbageCollectorLength - 2] ?>"
}
The reason this isn’t working is because JavaScript is executed in the client’s browser, where the PHP is executed on the server. So in the initial load, you’re getting what you’d expect because as the page was being created, PHP got the contents of that file. After that, however, PHP is gone and out of the picture.
You’ll probably need to look into using AJAX to periodically refresh the contents.