user1667374
user1667374

Reputation: 161

How to delete files matching pattern within a directory in PHP?

I have created a PHP script to generate CSV files. I want to keep only the latest file which the script creates. How can I delete all older *.csv files in a directory using PHP?

Upvotes: 3

Views: 3972

Answers (1)

alex
alex

Reputation: 490253

// Get a list of all CSV files in your folder.
$csv = glob("*.csv");

// Sort them by modification date.
usort($csv, function($a, $b) { return filemtime($a) - filemtime($b); });

// Remove the newest from your list.
array_pop($csv);

// Delete all the rest.
array_map('unlink', $csv);

If your CSV extension may be any case, swap csv with [cC][sS][vV]. This is a glob pattern.

Upvotes: 11

Related Questions