Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP delete the contents of a directory

How do I do that? Is there any method provided by kohana 3?

like image 821
ed. Avatar asked Feb 05 '10 05:02

ed.


People also ask

How do I empty a directory in PHP?

The rmdir() function in PHP is an inbuilt function which is used to remove an empty directory. It is mandatory for the directory to be empty, and it must have the relevant permissions which are required to delete the directory.

How do I delete files from a directory?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

How can you delete file from PHP?

To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.

Which function is used in PHP to delete a file?

PHP | unlink() Function The unlink() function is an inbuilt function in PHP which is used to delete files.


1 Answers

To delete a directory and all this content, you'll have to write some recursive deletion function -- or use one that already exists.

You can find some examples in the user's notes on the documentation page of rmdir ; for instance, here's the one proposed by bcairns in august 2009 (quoting) :

<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?> 
like image 116
Pascal MARTIN Avatar answered Oct 23 '22 09:10

Pascal MARTIN