问题
It's possible to listen folders and files changes (by events) on PHP or Node directly, or I need make my own method to do it?
Example: I need to listen the folder /user
. If I add some file into this directory the PHP or Node receives the information and run PathEvent::fileAdded("/user/user.profile")
for instance. If I rename a folder it run PathEvent::pathRenamed("/user/save1", "/user/save2")
.
I know that PHP don't have an event system like Node. But for PHP I can, for instance, run a method (that I don't know currently) that have the changes ocurred since last time checked.
Well... I need only a way to start searching, I don't know exactly what is the term of this search. If you can show me an example, it'll be great too! :P
回答1:
Node.js provides this functionality. You can read bout this here.
Simple example:
var fs = require('fs');
fs.watch('somedir', function (event, filename) {
console.log(event);
console.log(filename);
});
Note:
When watching a directory, providing filename argument in the callback is not supported on every platform (currently it's only supported on Linux and Windows). Even on supported platforms filename is not always guaranteed to be provided. Therefore, don't assume that filename argument is always provided in the callback, and have some fallback logic if it is null.
回答2:
If you have access to the way files would be accessed/changed/added etc. I would create couple of tables in DB. One for types of change and one for change and its time stamp.
When someone does something to a file ie rename. It goes via your wrapper that also adds an insert to db with current timestamp. When your PHP script runs you can pull all changes since last. So
select * from Log where ModifiedOn > $lastRun
.
This is how I'm tracking changes to DB tables. I hope that helps.
回答3:
For anyone looking for a PHP solution, you can use the inotify extension. https://www.php.net/manual/en/book.inotify.php
Note that since PHP itself is not event driven, using this probably only makes sense if you are running PHP as a daemon process and a library that provides an event loop. The watchers can be used with stream_select()
along with any other I/O you are listening for.
来源:https://stackoverflow.com/questions/9628074/listening-folders-and-files-changes