在PHP中更新文件时更新数据库信息

时间:2015-03-17 06:23:59

标签: php mysql

我有一个数据库(MySQL)表,它存储可以下载的文件的链接,它还包含上次更新这些文件的时间。

每当我运行代码来更新cPanel中FileManager中的文件时,我希望数据库表中的时间值(时间戳)发生变化。

我如何在PHP中执行此操作?我试着搜索,但无济于事。需要一些指导。

到目前为止,我所做的是创建一个接口,以便我可以使用SB Admin v2.0在数据库中插入文件。这需要更新时间值。但是,我不需要界面,因为我将运行代码来更新文件。

所以我要看的是如何使用PHP获取文件的最后修改时间?

2 个答案:

答案 0 :(得分:1)

如果您通过外部脚本(而非PHP)更新文件系统,则需要“监听”文件。为此,请使用Cron Job运行此(伪)代码。

$files = array(
    'file1.txt' => array('timestamp' => '12345678'),
    'file2.txt' => array('timestamp' => '12346879'),
);

$target = '/uploads'; 
$weeds = array('.', '..'); 
$uploadedFiles = array_diff(scandir($target), $weeds); 

foreach ($uploadedFiles as $filename) {
    if (isset($files[$filename])) {
        if ($files[$filename]['timestamp'] < filemtime($filename)) {
            $db->update('UPDATE files SET timestamp = :timestamp WHERE file_name = :filename');
            $db->params = array_merge($db->params, array(':filename' => $filename, ':timestamp' => $files[$filename]['timestamp']));
        }
    } else {
        $db->insert(getFileInfo($filename));
    }
}

答案 1 :(得分:0)

您可以使用https://github.com/crodas/WatchFiles。示例代码取自自述文件。

require "vendor/autoload.php";

use WatchFiles\Watch;

// we'd like to watch some files
// and to save its state in foobar.php
$foobar = new Watch("foobar.php");
if ($foobar->isWatching()) {
  if (!$foobar->hasChanged()) {
    // somebody else before us started watching files/dirs
    // on foobar.php and *nothing* changed since last 
    // time
    return;
  }
  // do heavy stuff here (Recompile it?)
  // we need to tell the watch that we're aware of lastest
  // changes and we'd like to update the file modification time
  $foobar->rebuild();
  return;
}

// we'd love to see when a new file has been added or deleted
$foobar->watchDir("foodir");
$foobar->watchDirs(array("foodir", 'foobar'));

// or monitor changes inside file or files
$foobar->watchFile("foodir.php");
$foobar->watchFiles(array("foodir.php", 'foobar.php'));

// start watching!
$foobar->watch();