這是一個基本的解決方案。
這是你的HTML和JS index.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Read Log File</title>
</head>
<body>
<div>
<ul id="log">
</ul>
</div>
<script src="./jquery-3.2.1.min.js"></script>
<script>
$(function(){
setInterval(function(){
$.getJSON("./getLog.php", function(data) {
var $log = $('#log');
$.each(data, function(key, val) {
$log.prepend("<li>" + val + "</li>");
});
});
},5000);
});
</script>
</body>
</html>
這是你的PHP文件getLog.php
<?php
session_start();
$file = '/path/to/your/file_log';
$total_lines = shell_exec('cat ' . escapeshellarg($file) . ' | wc -l');
if(isset($_SESSION['current_line']) && $_SESSION['current_line'] < $total_lines){
$lines = shell_exec('tail -n' . ($total_lines - $_SESSION['current_line']) . ' ' . escapeshellarg($file));
} else if(!isset($_SESSION['current_line'])){
$lines = shell_exec('tail -n100 ' . escapeshellarg($file));
}
$_SESSION['current_line'] = $total_lines;
$lines_array = array_filter(preg_split('#[\r\n]+#', trim($lines)));
if(count($lines_array)){
echo json_encode($lines_array);
}
?>
你必須使用一個計時器+ AJAX通過JavaScript調用PHP腳本來獲得最新的線路。 – aynber
[PHP - 返回文件中的最後一行?]可能的重複(https://stackoverflow.com/questions/1062716/php-returning-the-last-line-in-a-file) – cmorrissey
@cmorrissey OP狀態:*「目前我只做了一次,但它工作正常,我只需要一種方法來實時更新它每秒」*。 –