I have been searching around for a faster method to accomplish prepending a log file. Below are the current two methods I know of. I have also explored appending the file normally and then reading the file in reverse to display but (without testing) I think this would take longer once the file gets to a reasonable size. What is the quickest method to prepend a log file?
$start1 = microtime(true);
log1();
$end1 = microtime(true);
$start2 = microtime(true);
// log2();
$end2 = microtime(true);
$t1 = $end1-$start1;
$t2 = $end2-$start2;
function log1(){
$stamp = date("Y-m-d @ h:i:sa");
$data = ($stamp." this has been a test of 1");
$data .= file_get_contents('./test.log');
file_put_contents('./test.log', "\r\n\r\n".$data);
}
EDIT: updated log2()
function log2(){
$stamp = date("Y-m-d @ h:i:sa");
$write = $stamp.'this has been a test of 2'.PHP_EOL;
$file = './test.log';
$handler = fopen($file, 'r+');
$len = strlen($write);
$final_len = filesize($file)+$len;
$cache_old = fread($handler, $len);
rewind($handler);
$i=1;
while(ftell($handler) < $final_len){
fwrite($handler, $write);
$write = $cache_old;
$cache_old = fread($handler, $len);
fseek($handler, $i * $len);
$i++;
}
fclose($handler);
}