How to delete all files except some files in codeigniter?

Member

by mac , in category: PHP Frameworks , 5 months ago

How to delete all files except some files in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 5 months ago

@mac 

You can use the PHP glob() function to retrieve a list of files in a directory, loop through them, and delete the files that you want to keep. Here's an example code snippet to achieve this in CodeIgniter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Specify the directory from which you want to delete files
$directory = "/path/to/directory/";

// List of files that you want to keep
$filesToKeep = array("file1.txt", "file2.jpg");

// Get a list of all files in the directory
$files = glob($directory . "*");

// Loop through the files and delete the ones that are not in the filesToKeep array
foreach($files as $file) {
    $filename = basename($file);
    if (!in_array($filename, $filesToKeep)) {
        unlink($file);
    }
}


Replace "/path/to/directory/" with the path to the directory from which you want to delete files, and update the $filesToKeep array with the list of files that you want to keep. The code will loop through all files in the directory and delete the ones that are not in the $filesToKeep array.