观察root并检查PHP

时间:2017-07-24 06:49:15

标签: php linux bash inotify

我想从FTP的根目录中查看文件夹。自动将根目录上传一些文件。我需要知道上传这个新文件的时间,我要做的是获取文件的名称,并在创建文件的情况下将名称添加到数据库中。

我看到人们建议使用inotify(Linux)。但是我无法理解代码是用bash还是用简单的php文件写的。如果有人可以帮我一个例子和完整的解释

这是在互联网上找到的一个例子

#!/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);
?>

1 个答案:

答案 0 :(得分:-1)

使用数组的快速和脏循环可以做到这一点。这是一个bash的例子;

#!/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