How to delete all files in folder using php

In this article,I will explain how to delete all files and subfolders in a directory with php script.
php function unlink is used to delete file and same function can be used to delete all the files in a directory. you can use rmdir() php function to delete empty directory.

Following code will delete all the files from a directory.
<?php
/***
  * deleteDir($directory) Function is used to Delete all files in directory.
  *
*/

function deleteDir($directory) {
   if (is_dir($directory))
         $dir = opendir($directory);
   else
      return false;
  
   while($file = readdir($dir)) {
  
      if ($file != "." && $file != "..")
   {
       //chmod($directory.$file, 0777);

         if (!is_dir($directory."/".$file))
            unlink($directory."/".$file);
         else
            deleteDir($directory.'/'.$file);   
      }
   }
   closedir($dir);
   rmdir($directory);
   return true;
}
//I have all my files in a directory called Test, and I need to remove all
files in a directory.
 $directory_name="Test";
 deleteDir($directory_name);

?>

You can also use below php Script to remove all files in a directory.

<php

// For linux
 $remove_directory = "rm -r /test/directory_name/*";
exec($remove_directory); 

 // For windows

 $remove_directory - "del /Q c:\\test\directory_name\*";
exec($remove_directory); 

?>

I hope This script will help you to delete all files and subfolders in a directory with php script.