Reputation: 193282
I need to touch a file from within one PHP script and read the last time this file was touched from within another script, but no matter how I touch the file and read out the modification date, the modification date doesn't change, below is a test file.
How can I touch the log file and thus change the modification date, and then read this modification date?
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();
Upvotes: 1
Views: 711
Reputation: 4634
You should use the function clearstatcache
found in the PHP Manual
PHP caches the information those functions(filemtime) return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.
Function:
protected function _getDateTimeLogFileLastTouched() {
clearstatcache();
return filemtime($this->log_file_name);
}
Upvotes: 3