gpt4 book ai didi

php - 观察 root 并检查 PHP 中的新文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:31 28 4
gpt4 key购买 nike

我想从 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);
?>

最佳答案

使用数组的快速而肮脏的循环可以做到这一点。这是一个 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

关于php - 观察 root 并检查 PHP 中的新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274239/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com