By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

How to Delete Files and Directories With PHP

This php tutorial shows how to delete files by name, and by first searching a given directory for files to be deleted.

Edited: 2014-12-28 04:36

Deleting files with PHP can be done with the unlink function. If you want to delete the entire contents of a directory, you may want to include the files in an array, then cycle trough this array with a loop, and delete the files one by one.

One of the main reasons to delete files, is to free up storage space. Deleting the entire contents of a directory is often done to make it possible to use rmdir to remove the directory itself.

Deleting a file is really simple, all you need to do, is to write the path for the file that you want to delete – an example of how to delete a .html file is shown below:


This only shows how to delete a single file, so lets show how to delete the entire contents of a given directory.

Delete the contents of a directory

To delete the contents of a directory with php, you can use the glob function to return the contents as an array, then cycle trough this array to delete files one by one.

$aFiles = glob("Cookies/*.txt");

$n = count($aFiles);
$counter = 0;
while ($counter < $n) {

You can also use a foreach loop to cycle trough the results directly, the below would delete the directory contents of "MyDirectory" one by one.

$dir = 'MyDirectory/';
  foreach(glob($dir.'*.*') as $item){

Deleting the directory contents is needed before you can delete the directory itself, which is done with the rmdir function, this is demonstrated in the below example:


See also

  1. Create and Write to Files
  2. Read Content of Files
  3. Copying Files
  4. Renaming Files