75 lines
1.7 KiB
PHP
75 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Lean;
|
|
|
|
class File
|
|
{
|
|
public static function tail(string $path, int $lines = 10) : false|array
|
|
{
|
|
$handle = fopen($path, "r");
|
|
|
|
$counter = $lines;
|
|
|
|
$pos = -2;
|
|
$beginning = false;
|
|
$text = array();
|
|
|
|
while ($counter && !$beginning) {
|
|
$t = "";
|
|
|
|
while ($t !== PHP_EOL) {
|
|
if (fseek($handle, $pos, SEEK_END) == -1) {
|
|
$beginning = true;
|
|
break;
|
|
}
|
|
|
|
$t = fgetc($handle);
|
|
$pos--;
|
|
}
|
|
|
|
$counter--;
|
|
|
|
if ($beginning) {
|
|
rewind($handle);
|
|
}
|
|
|
|
$text[$lines - $counter - 1] = fgets($handle);
|
|
}
|
|
|
|
fclose($handle);
|
|
|
|
return array_reverse($text);
|
|
}
|
|
|
|
public static function sanitizeFilePath($path) : string
|
|
{
|
|
// Remove null bytes
|
|
$path = str_replace("\0", "", $path);
|
|
|
|
$path = str_replace([ "\\", "/" ], DIRECTORY_SEPARATOR, $path);
|
|
|
|
$path = preg_replace('#' . DIRECTORY_SEPARATOR . '+#', DIRECTORY_SEPARATOR, $path);
|
|
|
|
// Remove . and .. directory traversal attempts
|
|
$path = preg_replace('#\.{1,2}/#', '', $path);
|
|
|
|
$path = trim($path, '/\\');
|
|
|
|
return $path;
|
|
}
|
|
|
|
public static function assertFileExists(string $filepath) : void
|
|
{
|
|
if (! is_file($filepath)) {
|
|
throw new \InvalidArgumentException("File does not exist: {$filepath}");
|
|
}
|
|
}
|
|
|
|
public static function assertFolderExists(string $path) : void
|
|
{
|
|
if (! is_dir($path)) {
|
|
throw new \InvalidArgumentException("Folder does not exist: {$path}");
|
|
}
|
|
}
|
|
|
|
} |