I want to watch a folder from root of FTP. Automatically will be uploaded in the root some files. I need to know when this new file is uploaded and what I have to do is to get the name of the file and to add the name into the database with the file created.
I saw the people recommends to use inotify (Linux). But I can't understand if the code will be write in bash or in a simple php file..If can someone can help me with an example and full explanation
Here an example found on the internet
#!/usr/local/bin/php
<?php
// directory to watch
$dirWatch = 'watch_dir';
// Open an inotify instance
$inoInst = inotify_init();
// this is needed so inotify_read while operate in non blocking mode
stream_set_blocking($inoInst, 0);
// watch if a file is created or deleted in our directory to watch
$watch_id = inotify_add_watch($inoInst, $dirWatch, IN_CREATE | IN_DELETE);
// not the best way but sufficient for this example :-)
while(true){
// read events (
// which is non blocking because of our use of stream_set_blocking
$events = inotify_read($inoInst);
// output data
print_r($events);
}
// stop watching our directory
inotify_rm_watch($inoInst, $watch_id);
// close our inotify instance
fclose($inoInst);
?>
A quick and dirty loop using an array could do it. Here's a bash example;
#!/bin/bash
dir="/path/to/files/"
delay=60 #seconds to sleep between checks
#Get list of files already existing at startup:
for i in $dir*; do
i="${i##*/}" #Isolates the file name from the path
knownlist+=("$i")
done
while true; do
sleep $delay
for i in $dir*; do
match=0
i="${i##*/}"
for ((ii=0;ii<${#knownlist[*]};ii++)); do
if [[ $i == $ii ]]; then match=1; break; fi
#Basically, for every file in $dir, we check against all files
#listed in the ${knownfiles} array, to see if any match.
done
if [[ match == 0 ]]; then
#No match was found, so this is a new file.
#Place your database commands here; $i holds the file's name
knownlist+=("$i") #File is now known, so we add it to the list
fi
done
done