-2

How can I remove ALL but .sql file extensions in a specific folder with php? It's a php file that is supposed to create a backup of the database and place it in a back up folder but if there are any .jpg or any other extensions it should remove them from the backup folder.

jarlh
  • 42,561
  • 8
  • 45
  • 63
Momo
  • 11
  • Using the code you profided us (nothing), browse the folder manually and sort on .SQL, delete the rest. – Xorifelse May 30 '16 at 10:29

2 Answers2

2

You can use glob:

$path = "backup/";

foreach(glob($path ."*.*") as $file) {
    $location = explode(".",$file);
    $extension = $location[count($location)-1];
    if($extension != "sql"){
        unlink($file);
    }
}

One liner:

foreach(glob("backup/*") as $file) {    
    if(pathinfo($file, PATHINFO_EXTENSION) != "sql") unlink($file);
}
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
2
foreach (glob("/path/to/folder/*") as $filename) {
    if(!pathinfo($filename)['extension'] == "sql"){
        unlink($filename);
    }
}

We use glob to final all files (*) inside /path/to/folder/
Then we check is the file extension isn't sql using !pathinfo($filename)['extension'] == "sql", if true, we delete the file.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Please try to add some explanation rather than just code. I know that it speaks to itself when you're experienced with it (as I am as well), but this will be seen by many, many people in it's lifetime. It came up in the LQ queue. – Will May 30 '16 at 12:17