1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebComplete\core\utils\helpers; |
4
|
|
|
|
5
|
|
|
class FileHelper |
6
|
|
|
{ |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Slightly modified version of http://www.geekality.net/2011/05/28/php-tail-tackling-large-files/ |
10
|
|
|
* |
11
|
|
|
* @author Torleif Berger, Lorenzo Stanco |
12
|
|
|
* @link http://stackoverflow.com/a/15025877/995958 |
13
|
|
|
* @license http://creativecommons.org/licenses/by/3.0/ |
14
|
|
|
* |
15
|
|
|
* @param string $filepath |
16
|
|
|
* @param int $lines |
17
|
|
|
* @param bool $adaptive |
18
|
|
|
* |
19
|
|
|
* @return bool|string |
20
|
|
|
*/ |
21
|
|
|
public static function tail(string $filepath, int $lines = 1, $adaptive = true) |
22
|
|
|
{ |
23
|
|
|
// Open file |
24
|
|
|
$file = @fopen($filepath, "rb"); |
25
|
|
|
if ($file === false) { |
26
|
|
|
return false; |
27
|
|
|
} |
28
|
|
|
// Sets buffer size, according to the number of lines to retrieve. |
29
|
|
|
// This gives a performance boost when reading a few lines from the file. |
30
|
|
|
if (!$adaptive) { |
31
|
|
|
$buffer = 4096; |
32
|
|
|
} else { |
33
|
|
|
$buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); |
34
|
|
|
} |
35
|
|
|
// Jump to last character |
36
|
|
|
fseek($file, -1, SEEK_END); |
37
|
|
|
// Read it and adjust line number if necessary |
38
|
|
|
// (Otherwise the result would be wrong if file doesn't end with a blank line) |
39
|
|
|
if (fread($file, 1) != "\n") { |
40
|
|
|
$lines -= 1; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// Start reading |
44
|
|
|
$output = ''; |
45
|
|
|
// While we would like more |
46
|
|
|
while (ftell($file) > 0 && $lines >= 0) { |
47
|
|
|
// Figure out how far back we should jump |
48
|
|
|
$seek = min(ftell($file), $buffer); |
49
|
|
|
// Do the jump (backwards, relative to where we are) |
50
|
|
|
fseek($file, -$seek, SEEK_CUR); |
51
|
|
|
// Read a chunk and prepend it to our output |
52
|
|
|
$output = ($chunk = fread($file, $seek)) . $output; |
53
|
|
|
// Jump back to where we started reading |
54
|
|
|
fseek($file, -mb_strlen($chunk, '8bit'), SEEK_CUR); |
55
|
|
|
// Decrease our line counter |
56
|
|
|
$lines -= substr_count($chunk, "\n"); |
57
|
|
|
} |
58
|
|
|
// While we have too many lines |
59
|
|
|
// (Because of buffer size we might have read too many) |
60
|
|
|
while ($lines++ < 0) { |
61
|
|
|
// Find first newline and remove all text before that |
62
|
|
|
$output = substr($output, strpos($output, "\n") + 1); |
63
|
|
|
} |
64
|
|
|
// Close file and return |
65
|
|
|
fclose($file); |
66
|
|
|
return trim($output); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|