How To Delete All Files In A Directory In PHP

Hello programmers, Today I am going to show you how to delete all files from a directory in PHP. I know sometimes its become very useful to delete all the files from a directory using PHP. ( delete all files in a directory PHP ).

So let us learn this with a small example.

Real Time Chat Application PHP With File Transfer System  AJAX

Suppose you have a directory named mydirectory.

Now in that directory, you have some files which you wanna delete running a PHP Script.

Also Read,

How to delete or remove array element in PHP?

How To Add text to image in PHP Watermarking

So, Now you need a PHP Script which will perform this task for you. That means a PHP Script to delete all the files from a directory.

So, let us create it.

$filelist = glob('mydirectory/*'); 
foreach($filelist as $myfiles){ 

Explanation of PHP Script To Delete All The Files From a Folder

So whenever you will run this PHP file all of your files will be deleted from the mydirectory folder.

$filelist variable is taken to store the file names as an array.

Here glob(‘myrirectory/*’) is used. Because we wanna get the file names from the directory mydirectory.

after the slash, we have used a star sign. Star means we wanna get all the files.

Next, foreach fool is responsible for getting the file names one by one from the array. if the file exists in that directory the unlink function gonna run.

unlink in PHP is responsible to delete a particular file. And here we are using the foreach loop and this loop will continue deleting each file until we reach at the end.

Hope you have learned to delete all files in a directory PHP

Free Currency Converter PHP using Fixer io API


Leave a Reply

Your email address will not be published. Required fields are marked *