请问php如何实时监听目录有新文件变化?
网友回复
第一种不需要安装东西直接通过while循环对比目录下文件夹的md5值是否有变动,代码如下:
<?php
class FileWatch
{
protected $all = array();
public function __construct($dir)
{
$this->watch($dir);
}
//子类中重写这个方法
public function run($file)
{
}
protected function all_file($dir)
{
if (is_file($dir)) {
$this->all[$dir] = md5_file($dir);
return $this->all;
}
if (is_dir($dir)) {
$open = opendir($dir);
while (($file = readdir($open)) !== false) {
if ($file != "." && $file != "..") {
$f = $dir . "/" . $file;
if (is_file($f)) {
$this->all[$f] = md5_file($f);
} elseif (is_dir($f)) {
$this->all_file($f);
}
}
}
}
return $this->all;
}
public function watch($dir)
{
$this->all = array();
$old = $this->all_file($dir);
while (true) {
sleep(2);
$this->all = array();
$new = $this->all_file($dir);
$re = array_diff($new, $old);
$del = array_diff_key($old, $new);
$re = array_merge($re, $del);
if ($re) {
$this->all = array();
$old = $this->all_file($dir);
$file = array_keys($re);
$this->run($file[0]);
}
}
}
}//endclass
//使用方法
class mywatch extends FileWatch
{
public function run($file)
{
if(!empty($file)) {
echo "new file or file has been changed with ".$file.PHP_EOL;
} else {
echo "no files has created and no files has been c...点击查看剩余70%
python能写一个检测nginx rewrite高危漏洞的工具代码?
css如何给video视频进行mask遮罩?
windows如何同时允许两个用户远程桌面连接同一个电脑?
nginx升级到1.30.1导致无法启动 [emerg] SSL_CTX_new() failed怎么办?
什么是ASLR(地址随机化)?
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?


