MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

XXXV. File Alteration Monitor Functions

Introducción

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.

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

Nota: Esta extensión no está disponible en plataformas Windows

Requisitos

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

Instalación

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.

Configuración en tiempo de ejecución

Esta extensión no tiene directivas de configuración en php.ini.

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

Tabla 1. FAM event constants

ConstantDescription
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.
Tabla de contenidos
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


add a note add a note User Contributed Notes
File Alteration Monitor Functions
Yassin Ezbakhe <yassin88 at gmail dot com>
31-Aug-2005 04:16
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();
}
ca50015 at yahoo dot com
27-Nov-2004 09:17
if u want do recursive monitoring on directory tree,
dont use fam_monitor_directory()
try to use fam_monitor_collection() instead
:)
b e n a d l e r -at- g m x -d-o-t- net
11-Aug-2004 10:57
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!
sergiopaternoster at no_spam_tiscali dot it
21-May-2004 09:20
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

Citas célebres

La ambición es el único poder que puede luchar contra el amor.

Colley Cibber
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_022.jpg
Contenidos Web

Chiste de... Camareros
Té sin leche, por favor.

- Camarero, tráigame un té sin leche.

- Lo siento, señor, no tenemos leche, ¿qué le parece un té sin crema?
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_022.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0278.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid