PHP: How to read a file live that is constantly being written to

后端 未结 5 734
逝去的感伤
逝去的感伤 2020-12-10 03:22

I want to read a log file that is constantly being written to. It resides on the same server as the application. The catch is the file gets written to every few seconds, and

5条回答
  •  星月不相逢
    2020-12-10 03:58

    For example :

    $log_file = '/tmp/test/log_file.log';
    
    $f = fopen($log_file, 'a+');
    $fr = fopen($log_file, 'r' );
    
    for ( $i = 1; $i < 10; $i++ )
    {
        fprintf($f, "Line: %u\n", $i);
        sleep(2);
        echo fread($fr, 1024) . "\n";
    }
    
    fclose($fr);
    fclose($f);
    
    //Or if you want use tail
    
    $f = fopen($log_file, 'a+');
    
    for ( $i = 1; $i < 10; $i++ )
    {
        fprintf($f, "Line: %u\n", $i);
        sleep(2);
        $result = array();
        exec( 'tail -n 1 ' . $log_file, $result );
        echo "\n".$result[0];
    }
    
    fclose($f);
    

提交回复
热议问题