Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the newest file in a directory in php

Tags:

directory

php

So I have this app that processes CSV files. I have a line of code to load the file.

$myFile = "data/FrontlineSMS_Message_Export_20120721.csv";  //The name of the CSV file $fh = fopen($myFile, 'r');                             //Open the file 

I would like to find a way in which I could look in the data directory and get the newest file (they all have date tags so they would be in order inside of data) and set the name equal to $myFile.

I really couldn't find and understand the documentation of php directories so any helpful resources would be appreciated as well. Thank you.

like image 934
Mike Avatar asked Jul 22 '12 02:07

Mike


People also ask

How can I get the last modified information of a file using PHP?

The filemtime() function is an inbuilt function that returns the last modification of the file content. It returns as a UNIX timestamp of the last modification time of a file and returns false on failure. The filename is passed by filemtime() as a parameter.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.


1 Answers

Here's an attempt using scandir, assuming the only files in the directory have timestamped filenames:

$files = scandir('data', SCANDIR_SORT_DESCENDING); $newest_file = $files[0]; 

We first list all files in the directory in descending order, then, whichever one is first in that list has the "greatest" filename — and therefore the greatest timestamp value — and is therefore the newest.

Note that scandir was added in PHP 5, but its documentation page shows how to implement that behavior in PHP 4.

like image 135
Matchu Avatar answered Sep 29 '22 15:09

Matchu