To delete a file using php, the easiest way is to use the php unlink() function.

unlink("./folder/file_name1.txt");

Deleting files with php is easy. We can use the php unlink() function to delete files

If we want to delete a file named “file_name.txt”, we can do this with the following php code:

unlink("./folder/file_name.txt");

Deleting Multiple Files with php

In php, it is easy to delete multiple files in a folder. To do so, we can use the php unlink() function in a loop.

Let’s say we have 5 files and we want to delete these 5 files.

We can put the 5 file names in an array, and then loop over that array calling the unlink() function inside the loop:

$files_to_delete = array("file1.php","file2.php","file3.php","file4.php","file5.php");

for ($x = 0; $x < 5; $x++) {
  unlink("./folder/" . $files_to_delete[$x]);
}

With this code, the 5 files will all be deleted.

Hopefully this article has been helpful for you to understand how you delete a file or delete multiple files using php.

Categorized in:

PHP,

Last Update: February 26, 2024