简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM