I am writing a simple PHP script to watch a folder and its subfolders for any changes (new files, modifications, deletions) and then perform an action.
I will run this script from the commandline on windows using php -f script.php
.
I have been search for a way to watch folders on windows that has PHP bindings. Something like inotify or gamin for windows would be nice.
The answers to this question mentions FindFirstChangeNotification
, but I couldn't find any PHP bindings for it.
Are there any libraries/software for folder/filesystem watching on windows with PHP bindings?
I ended up just writing a simple function using the RecursiveDirectoryIterator
that is called in an infinit loop.
All I have to do is check the last modified time of the file or a folder and return true or false.
This isn't a very exact approach, but it serves my purposes well. Sitting in the back ground, the script uses about 12MB of ram.
You can use inotify_add_watch PHP function to get notification of any changes (new files, modifications, deletions) in specified directory. It works the same way as FileSystemWatcher on Windows.
If you have Ruby installed on your server you can use watchr gem
What it does is very simple, upon fire/directory change it executes a script defined by you which is exactly what you're trying to do.
Here is an example file autotest.rb
:
#!/usr/bin/ruby
# Match all PHP files in your project directory
watch("<PROJECT_DIR_PATH>/(.*).<FILE_EXTENSION_PHP>") do |match|
run_test %{<PROJECT_DIR_PATH>/Tests/#{match[1]}Test.php}
end
# Match all files in your Tests directory
watch("<PROJECT_DIR_PATH>/Tests/.*Test.php") do |match|
run_test match[0]
end
# Run test if there are matches
def run_test(file)
unless File.exist?(file)
puts "#{file} does not exist"
return
end
puts "Running #{file}"
result = `phpunit #{file}`
puts result
end
So this wil match all PHP or any other extension files and run RegEx against the name of the file and if there is a match like /Project/Tests/ClassNameTest.php it will run the test otherwise just terminate with massage. For convenience this could be set to send emails upon errors to predefined list emails.