Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 627
user1667374 Avatar asked Oct 16 '25 03:10

user1667374


1 Answers

// 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.

like image 84
alex Avatar answered Oct 17 '25 17:10

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!