From 2fb022461ebd95251dec7918e63279a5f594f885 Mon Sep 17 00:00:00 2001 From: = <=> Date: Fri, 9 Feb 2024 22:39:08 +0200 Subject: [PATCH] First implementation --- .gitignore | 3 +++ README.md | 36 +++++++++++++++++++++++++++++++++- composer.json | 17 ++++++++++++++++ example.php | 14 +++++++++++++ src/Monitor.php | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 composer.json create mode 100644 example.php create mode 100644 src/Monitor.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8925195 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +vendor +composer.lock \ No newline at end of file diff --git a/README.md b/README.md index 1dd2400..fb958a0 100644 --- a/README.md +++ b/README.md @@ -1 +1,35 @@ -# php-tail-f \ No newline at end of file +# tail -f for PHP + +A simple implementation to provide "tail -f" functionality in PHP code. Allows you to monitor newly added lines to a given file. + +This class is designed for implementation within a PHP daemon, specifically excluding its suitability for PHP scripts that generate output for web browsers. + +It is a lightweight class that minimally consumes RAM, CPU, or disk I/O resources. + +## Sample usage + +```php +run() as $output) { + echo $output; +} +``` + + +## Authors + +* [Nico Hiort af Ornäs](https://github.com/nicodemuz) + +## Credits + +Based on the work from https://github.com/Basch3000/php-tail \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..3f81e10 --- /dev/null +++ b/composer.json @@ -0,0 +1,17 @@ +{ + "name": "nicodemuz/php-tail-f", + "description": "Provides tail -f functionailty to watch changes in files", + "type": "library", + "license": "MIT", + "autoload": { + "psr-4": { + "Nicodemuz\\PhpTailF\\": "src/" + } + }, + "authors": [ + { + "name": "Nico Hiort af Ornäs" + } + ], + "require": {} +} diff --git a/example.php b/example.php new file mode 100644 index 0000000..4deb60b --- /dev/null +++ b/example.php @@ -0,0 +1,14 @@ +run() as $output) { + echo $output; +} diff --git a/src/Monitor.php b/src/Monitor.php new file mode 100644 index 0000000..7a3a821 --- /dev/null +++ b/src/Monitor.php @@ -0,0 +1,52 @@ +filePath, "r"); + while(true) + { + clearstatcache(false, $this->filePath); + $modified = filemtime($this->filePath); + + if($modified == $this->lastModified) { + usleep($this->sleepMicroseconds); + continue; + } + + $this->lastModified = $modified; + + $lastSize = filesize($this->filePath); + $bytesAdded = $lastSize - $this->lastSize; + $this->lastSize = $lastSize; + + if($bytesAdded == $lastSize) + { + fseek($filePointer, $lastSize); + usleep($this->sleepMicroseconds); + continue; + } + + fseek($filePointer, -$bytesAdded); + $added = fread($filePointer, $lastSize); + + yield $added; + + usleep($this->sleepMicroseconds); + } + } +} \ No newline at end of file