[英]How to get the newest file in a directory in php
所以我有這個處理 CSV 文件的應用程序。 我有一行代碼來加載文件。
$myFile = "data/FrontlineSMS_Message_Export_20120721.csv"; //The name of the CSV file
$fh = fopen($myFile, 'r'); //Open the file
我想找到一種方法,我可以在其中查看data
目錄並獲取最新文件(它們都有日期標簽,因此它們在data
中按順序排列)並將名稱設置為$myFile
。
我真的無法找到和理解 php 目錄的文檔,因此也將不勝感激任何有用的資源。 謝謝你。
對於使用通配符的搜索,您可以使用:
<?php
$path = "/var/www/html/*";
$latest_ctime = 0;
$latest_filename = '';
$files = glob($path);
foreach($files as $file)
{
if (is_file($file) && filectime($file) > $latest_ctime)
{
$latest_ctime = filectime($file);
$latest_filename = $file;
}
}
return $latest_filename;
?>
我的解決方案,來自 Max Hofmann 的改進解決方案:
$ret = [];
$dir = Yii::getAlias("@app") . "/web/uploads/problem-letters/{$this->id}"; // set directory in question
if(is_dir($dir)) {
$ret = array_diff(scandir($dir), array(".", "..")); // get all files in dir as array and remove . and .. from it
}
usort($ret, function ($a, $b) use ($dir) {
if(filectime($dir . "/" . $a) < filectime($dir . "/" . $b)) {
return -1;
} else if(filectime($dir . "/" . $a) == filectime($dir . "/" . $b)) {
return 0;
} else {
return 1;
}
}); // sort array by file creation time, older first
echo $ret[count($ret)-1]; // filename of last created file
下面是一個例子,我對使用自己的驗證器更有信心,而不是簡單地依賴scandir () 的時間戳。
在這種情況下,我想檢查我的服務器是否有比客戶端版本更新的文件版本。 所以我比較文件名中的版本號。
$clientAppVersion = "1.0.5";
$latestVersionFileName = "";
$directory = "../../download/updates/darwin/"
$arrayOfFiles = scandir($directory);
foreach ($arrayOfFiles as $file) {
if (is_file($directory . $file)) {
// Your custom code here... For example:
$serverFileVersion = getVersionNumberFromFileName($file);
if (isVersionNumberGreater($serverFileVersion, $clientAppVersion)) {
$latestVersionFileName = $file;
}
}
}
// function declarations in my php file (used in the forEach loop)
function getVersionNumberFromFileName($fileName) {
// extract the version number with regEx replacement
return preg_replace("/Finance D - Tenue de livres-darwin-(x64|arm64)-|\.zip/", "", $fileName);
}
function removeAllNonDigits($semanticVersionString) {
// use regex replacement to keep only numeric values in the semantic version string
return preg_replace("/\D+/", "", $semanticVersionString);
}
function isVersionNumberGreater($serverFileVersion, $clientFileVersion): bool {
// receives two semantic versions (1.0.4) and compares their numeric value (104)
// true when server version is greater than client version (105 > 104)
return removeAllNonDigits($serverFileVersion) > removeAllNonDigits($clientFileVersion);
}
使用此手動比較而不是時間戳,我可以獲得更手術的結果。 如果您有類似的需求,我希望這可以給您一些有用的想法。
(PS:我花時間發帖是因為我對找到的與我的特定要求相關的答案不滿意。請客氣,我也不太習慣 StackOverflow - 謝謝!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.