0

How can I delete all files with a PHP script on a server? My problem is that I have many files that need to be deleted and over the FTP client it takes quite a long time.

Syntax6
  • 95
  • 1
  • 3
  • 10
  • Use `glob()` to get an array of all the files matching a wildcard pattern, and then loop over them calling `unlink()`. What's the problem? – Barmar Dec 02 '16 at 18:00
  • 1
    Can you edit this to add a bit more specific description of the problem? Where are the files you want to delete in relation to the PHP script? Are they on the same server? – Don't Panic Dec 02 '16 at 18:01
  • The data is stored on a server by an Internetprovider. I installed a shop system and generated just over 45000 files. Now I wanted to delete all data. With FileZilla it just takes too long. That is why I am looking for a PHP script, where the server directly takes over the work. I would expect a speed advantage. – Syntax6 Dec 02 '16 at 18:16
  • 3
    Possible duplicate of [Deleting all files from a folder using PHP?](http://stackoverflow.com/questions/4594180/deleting-all-files-from-a-folder-using-php) – nicovank Dec 02 '16 at 19:17

2 Answers2

2

you can delete all files using for loop, example: `

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

`

Kenly
  • 24,317
  • 7
  • 44
  • 60
0

Untested but this should work:

$dir = "dir/to/purge/"; // Directory you want to remove all the files from
$listing = scandir($dir); // Array containing all files and directories inside the provided directory

foreach($listing as $file) {
  if(is_file($dir . $file)) {
    unlink($dir . $file); // Removes the file from the listing
  }
}

Note that with a lot of files this could use up all your memory.

robere2
  • 1,689
  • 2
  • 16
  • 26
  • I think it should actually work, but it does not. I have made a PHP file from your code and uploaded it to the server. Then I called the file with the browser. Sorry, the directory has not been deleted. I think I have made a mistake. – Syntax6 Dec 02 '16 at 18:43
  • 1
    *"This will remove directories, too"* - `unlink()` only removes files, not folders. `rmdir()` removes folders but only if they're empty. – Funk Forty Niner Dec 02 '16 at 18:57
  • Fred that makes sense, didn't think about that. In that case, the latter should be used anyway. If you used the first version that could be the cause of your issue too, @Syntax6. Try the other one or use one of the other answers on this question. I'm editing my answer now to remove the first one. – robere2 Dec 02 '16 at 19:08