我在類中有一個方法,它檢查檔案是否超過一天。它通過獲取檔案的最后更改日期并將其與“現在”進行比較來實作這一點:
private function checkFileOutdated(string $filePath): bool
{
if (file_exists($filePath)) {
$fileTimeStamp = filectime($filePath);
$now = new DateTimeImmutable();
$fileDate = new DateTimeImmutable('@' . $fileTimeStamp);
$diff = (int) $now->format('Ymd') - (int) $fileDate->format('Ymd');
return $diff > 0;
}
return true;
}
我想撰寫一個偽造過時檔案的 Unittest。我嘗試通過觸摸更改檔案日期:
$location = '/var/www/var/xls/myfile.xlsx';
$handle = fopen($location, 'wb');
fclose($handle);
exec('touch -a -m -t 202109231158 ' . $location);
exec('ls -hl ' . $location, $output);
var_dump($output);
輸出給了我資訊,實際上我的檔案來自“Sep 23 11:58”,是的.....
但是我的測驗失敗了,當我除錯時,我的檔案日期是今天而不是 9 月,即 23 日。
使用 filemtime 結果相同。
是否可以偽造檔案時間戳?
我的系統在 alpine linux 上運行。
uj5u.com熱心網友回復:
請注意,您不必先創建檔案,因為 touch 會為您完成此操作。并且有一個內置的 PHP touch(),你不必shell exec:
touch('/tmp/foo', strtotime('-1 day'));
echo date('r', fileatime('/tmp/foo')), "\n";
echo date('r', filectime('/tmp/foo')), "\n";
echo date('r', filemtime('/tmp/foo')), "\n";
這產生:
Tue, 02 Nov 2021 12:18:17 -0400
Wed, 03 Nov 2021 12:18:17 -0400
Tue, 02 Nov 2021 12:18:17 -0400
應用您的代碼,但使用filemtime:
$fileTimeStamp = filemtime($filePath);
$now = new DateTimeImmutable();
$fileDate = new DateTimeImmutable('@' . $fileTimeStamp);
$diff = (int) $now->format('Ymd') - (int) $fileDate->format('Ymd');
var_dump($diff);
產生所需的真實值:
1
然而,這是一個相當迂回的比較。我只是直接比較時間戳值:
return filemtime('/tmp/foo') <= strtotime('-1 day');
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346789.html
下一篇:ulimit-t的有效值是多少?
