1

我需要从一个 PHP 脚本中触摸一个文件并读取上次从另一个脚本中触摸该文件的时间,但是无论我如何触摸文件并读出修改日期,修改日期都不会改变,下面是一个测试文件。

如何触摸日志文件从而更改修改日期,然后读取此修改日期?

class TestKeepAlive {

    protected $log_file_name;

    public function process() {
        $this->log_file_name = 'test_keepalive_log.txt';
        $this->_writeProcessIdToLogFile();

        for ($index = 0; $index < 10; $index++) {
            echo 'test' . PHP_EOL;
            sleep(1);
            touch($this->log_file_name);
            $this->_touchLogFile();
            $dateTimeLastTouched = $this->_getDateTimeLogFileLastTouched();
            echo $dateTimeLastTouched . PHP_EOL;
        }
    }

    protected function _touchLogFile() {
        //touch($this->log_file_name);
        exec("touch {$this->log_file_name}");
    }

    protected function _getDateTimeLogFileLastTouched() {
        return filemtime($this->log_file_name);
    }

    protected function _writeProcessIdToLogFile() {
        file_put_contents($this->log_file_name, getmypid());
    }

}

$testKeepAlive = new TestKeepAlive();
$testKeepAlive->process();
4

1 回答 1

3

您应该使用PHP 手册clearstatcache中的函数

PHP 缓存这些函数(filemtime)返回的信息以提供更快的性能。但是,在某些情况下,您可能需要清除缓存的信息。例如,如果在一个脚本中多次检查同一个文件,并且该文件在该脚本的操作期间有被删除或更改的危险,您可以选择清除状态缓存。在这些情况下,您可以使用 clearstatcache() 函数来清除 PHP 缓存的有关文件的信息。

功能:

protected function _getDateTimeLogFileLastTouched() {
    clearstatcache();
    return filemtime($this->log_file_name);
}
于 2013-02-04T17:19:01.087 回答