Guest User

PHP script: watch & replicate a folder's content in another

a guest
Mar 12th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.75 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?
  3. /*
  4.     Commands to install PHP-CLI, PEAR and iNotify plugin on Debian/Ubuntu:
  5.         sudo apt-get install php5-cli php5-dev php-pear libnotify-bin
  6.         sudo pecl install channel://pecl.php.net/inotify-0.1.4
  7.         sudo echo "extension=inotify.so" > /etc/php5/cli/conf.d/inotify.ini
  8. */
  9.  
  10. $dirToWatch = '/mnt/files/folderToWatch/';      // don't forget trailing slash.
  11. $destinationDir = '/mnt/files/destination/';    // don't forget trailing slash.
  12.  
  13.  
  14. $fd = null;
  15. $watch_descriptor = null;
  16.  
  17. // gracefully exit handler (unregister inotify)
  18. function shutdown($signo) {
  19.     global $fd, $watch_descriptor;
  20.     print("About to gracefully exit.\n");
  21.     if ($fd !== null) {
  22.         if ($watch_descriptor !== null) {
  23.             inotify_rm_watch($fd, $watch_descriptor);  
  24.             $watch_descriptor = null;  
  25.         }
  26.         fclose($fd);
  27.         $fd = null;
  28.     }
  29. }
  30. pcntl_signal(SIGTERM, "shutdown");
  31. pcntl_signal(SIGHUP,  "shutdown");
  32. pcntl_signal(SIGINT, "shutdown");
  33.  
  34. $fd = inotify_init();
  35. $watch_descriptor = inotify_add_watch($fd, $dirToWatch, IN_CREATE|IN_DELETE|IN_MOVED_TO|IN_MOVED_FROM);
  36. $doContinue = true;
  37. while ($doContinue) {
  38.     $events = @inotify_read($fd);
  39.     if ($events === false) shutdown(null);
  40.  
  41.     while (count($events)>0) {
  42.         $event = array_shift($events);
  43.         $filename = $event['name'];
  44.         $filepath = $dirToWatch . $filename;
  45.        
  46.         // when a new file appears in dirToWatch
  47.         if ( ($event['mask'] & (IN_CREATE|IN_MOVED_TO)) > 0) {
  48.             if (!is_link($destinationDir.$filename)) {
  49.                 symlink($filepath, $destinationDir.$filename);
  50.             }
  51.         }
  52.         // when a file is removed from dirToWatch
  53.         else if ( ($event['mask'] & (IN_DELETE|IN_MOVED_FROM)) > 0) {
  54.             if (is_link($destinationDir.$filename)) {
  55.                 unlink($destinationDir.$filename);
  56.             }
  57.         }
  58.         else {
  59.             // do nothing.
  60.         }
  61.     }
  62. }
  63.  
  64. ?>
Add Comment
Please, Sign In to add comment