HomeLập trình

Tìm file đã sửa mới nhất trong thư mục PHP

Like Tweet Pin it Share Share Email

Có rất nhiều dự án cần xử lý file trong php. Mình cũng đang gặp phải và đã trích bài toán này ra để lưu trữ vào blog này cho mình sử dụng về sau hoặc cho ai đó cần.

Bài toán:
Tìm file mới nhất của các file trong thư mục và hiển thị tên file và thời gian mới nhất của file bằng PHP.

Các bước:
1. Mở thư mục
2. Mở file
3. So sánh thời gian của file để lấy ra file mới nhất và thời gian mới nhất.
4. Đóng file
5. Hiển thị ra kết quả.

Đây là hình ảnh của thư mục mình muốn lấy:

Đoạn code file php:

<?php
 $directory= "D:\backup\aws\Invoice";
 $smallest_time=0;
 $latest_file='';
 if ($handle = opendir($directory)) {
     while (false !== ($file = readdir($handle))) {
         $time=filemtime($directory.'/'.$file);
         if (is_file($directory.'/'.$file)) {
             if ($time > $smallest_time) {
                 $latest_file = $file;
                 $smallest_time = $time;
             }
         }
     }
     closedir($handle);
  $lastModified = date("Y/m/d H:i:s", $smallest_time); 
 }
 echo $latest_file.' - '.$lastModified;

Kết quả:

Hy vọng bài toán này sẽ giúp ích được cho các bạn.

Tham khảo thêm cách tìm thời gian mới nhất của file trong thư mục bằng PHP:

$lastestTimeUserCoordination = array_values(File::allfiles(storage_path($backupInsertPath))); 
             $fixTime = 0;             
             foreach($lastestTimeUserCoordination  as $lastestTime){                 
                 $currentModified  = filemtime($lastestTime);               
                 if($fixTime < $currentModified ){
                     $fixTime = $currentModified ;
                     
                 }                
             }
             $lastModified = date("Y年m月d日 H時i分s秒", $fixTime); 

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *