Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : File Alteration Monitor Functions

File Alteration Monitor Functions

Introduction

FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at » http://oss.sgi.com/projects/fam/.

A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.

The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note:

This extension is not available on Windows platforms.

Requirements

This extension uses the functions of the » FAM library, developed by SGI. Therefore you have to download and install the FAM library.

Installation

To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

There are two resource types used in the FAM module. The first one is the connection to the FAM service returned by fam_open(), the second a monitoring resource returned by the fam_monitor_XXX functions.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 89. FAM event constants

Constant Description
FAMChanged (integer) Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) A file or directory was deleted or renamed.
FAMStartExecuting (integer) An executable file started executing.
FAMStopExecuting (integer) An executable file that was running finished.
FAMCreated (integer) A file was created in a directory.
FAMMoved (integer) This event never occurs.
FAMAcknowledge (integer) An event in response to fam_cancel_monitor().
FAMExists (integer) An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) Event after the last FAMEExists event.


Table of Contents

fam_cancel_monitor — Terminate monitoring
fam_close — Close FAM connection
fam_monitor_collection — Monitor a collection of files in a directory for changes
fam_monitor_directory — Monitor a directory for changes
fam_monitor_file — Monitor a regular file for changes
fam_next_event — Get next pending FAM event
fam_open — Open connection to FAM daemon
fam_pending — Check for pending FAM events
fam_resume_monitor — Resume suspended monitoring
fam_suspend_monitor — Temporarily suspend monitoring

Code Examples / Notes » ref.fam

b e n a d l e r -at- g m x -d-o-t- net

in the example above, I would not use the while(1) and sleep() functions, since then you're back at waiting and polling for file changes, which you were trying to avoid using fam.
Instead, you can use while(fam_next_event($resource)), which blocks until there is an event. No polling, no useless wasting of cpu  cycles.
Anyway, I have some problems with fam: It is very limited and almost useless.
- You cannot monitor a directory tree easily, since fam_monitor_directory() is non-recursive. Its an ugly hack, but you can go through each subdir and also monitor it with fam_monitor_directory().
- When you do that, you will have another problem: The events you get contain the code and the filename, but not the pathname of the file that caused the event. Thus, if you monitor two or more directories, and they possibly contain files with the same basename, you cannot find out what file has changed. One ugly solution might be to create a new fam_resource for each directory you want to monitor, but then you cannot use fam_next_event() in your while loop anymore.
- When a big file is saved (i.e. with photoshop via samba), you get file_changed events pretty much every second the file is being written to. It is not possible to receive ONE event AFTER the file operation is done.
I'm not sure, but I think most of this is not PHPs fault. Its just that fam (or dnotify, which fam uses on linux) sucks very badly. If you search on google, it seems everyone hates fam/dnotify (even linus), but noone has done anything about it yet.
If you find out how to work around thing, or if I'm completely wrong about all of this, please post here! Thanks!


ca50015

if u want do recursive monitoring on directory tree,
dont use fam_monitor_directory()
try to use fam_monitor_collection() instead
:)


yassin ezbakhe
I make a VERY simple class that monitors a folder (and its subfolders) for new or removed files. I use it in order to auto index a folder where I have all my eBooks into a MySQL database.
CLASS FILE:
<?php
class FileAlterationMonitor
{
   private $scanFolder, $initialFoundFiles;
   public function __construct($scanFolder)
   {
       $this->scanFolder = $scanFolder;
       $this->updateMonitor();
   }
   private function _arrayValuesRecursive($array)
   {
       $arrayValues = array();
       foreach ($array as $value)
       {
           if (is_scalar($value) OR is_resource($value))
           {
                $arrayValues[] = $value;
           }
           elseif (is_array($value))
           {
                $arrayValues = array_merge( $arrayValues, $this->_arrayValuesRecursive($value));
           }
       }
       return $arrayValues;
   }
   private function _scanDirRecursive($directory)
   {
       $folderContents = array();
       $directory = realpath($directory).DIRECTORY_SEPARATOR;
       foreach (scandir($directory) as $folderItem)
       {
           if ($folderItem != "." AND $folderItem != "..")
           {
               if (is_dir($directory.$folderItem.DIRECTORY_SEPARATOR))
               {
                   $folderContents[$folderItem] = $this->_scanDirRecursive( $directory.$folderItem."\\");
               }
               else
               {
                   $folderContents[] = $folderItem;
               }
           }
       }
       return $folderContents;
   }
   public function getNewFiles()
   {
       $finalFoundFiles = $this->_arrayValuesRecursive( $this->_scanDirRecursive($this->scanFolder));
       if ($this->initialFoundFiles != $finalFoundFiles)
       {
           $newFiles = array_diff($finalFoundFiles, $this->initialFoundFiles);
           return empty($newFiles) ? FALSE : $newFiles;
       }
   }
   public function getRemovedFiles()
   {
       $finalFoundFiles = $this->_arrayValuesRecursive( $this->_scanDirRecursive($this->scanFolder));
       if ($this->initialFoundFiles != $finalFoundFiles)
       {
           $removedFiles = array_diff( $this->initialFoundFiles, $finalFoundFiles);
           return empty($removedFiles) ? FALSE : $removedFiles;
       }
   }
   public function updateMonitor()
   {
       $this->initialFoundFiles = $this->_arrayValuesRecursive($this->_scanDirRecursive( $this->scanFolder));
   }
}
?>
A simple script that uses this class could be like this one (use it with PHP CLI):
<?php
$f = new FileAlterationMonitor($MY_FOLDER_TO_MONITOR)
while (TRUE)
{
   sleep(1);
   if ($newFiles = $f->getNewFiles())
   {
       // Code to handle new files
       // $newFiles is an array that contains added files
   }
   if ($removedFiles = $f->getRemovedFiles())
   {
       // Code to handle removed files
       // $newFiles is an array that contains removed files
   }
   $f->updateMonitor();
}


sergiopaternoster

Here is a simple script to check changes etc. to a file.
<?php
/* opens a connection to the FAM service daemon */
$fam_res = fam_open ();
/*
* The second argument is the full pathname
* of the file to monitor.
* Note that you can't use relative pathnames.
*/
$nres = fam_monitor_file ( $fam_res, '/home/sergio/test/fam/file_to_monitor.log');
while(1){
if( fam_pending ( $fam_res ) ) $arr = (fam_next_event($fam_res)) ;
switch ($arr['code']){
case 1:
echo "FAMChanged\n";
break;
case 2:
echo "FAMDeleted\n";
break;
case 3:
echo "FAMStartExecuting\n";
break;
case 4:
echo "FAMStopExecuting\n";
break;
case 5:
echo "FAMCreated\n";
break;
case 6:
echo "FAMMoved\n";
break;
case 7:
echo "FAMAcknowledge\n";
break;
case 8:
echo "FAMExists\n";
break;
case 9:
echo "FAMEndExist\n";
break;
default:
break;
}
if(isset($arr)) unset($arr);

/* In order to avoid too much CPU load */
usleep(5000);
}
/* Close FAM connection */
fam_close($fam_res);
?>
Hope this could help.
God Belss PHP!
regards
Sergio Paternoster


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker