Home » Php » Delete a folder already exist php

Delete a folder already exist php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.

 $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
                    $filename2 = $filename . '/' . $month;
                    if (file_exists($filename)) {
                        if (file_exists($filename2) == false) {
                            mkdir($filename2, 0777);
                        }
                    } else {
                        mkdir($filename, 0777);
                    }

If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code

rmdir($filename2)

but its not working.

please help me

How to&Answers:

Use this function for delete file.

unlink( $filepath)

Answer:

<?php

delete_files('/path/for/the/directory/');

/* 
 * php delete function that deals with directories recursively
 */
function delete_files($target) {
    if(is_dir($target)){
        $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

        foreach( $files as $file ){
            delete_files( $file );      
        }

        rmdir( $target );
    } elseif(is_file($target)) {
        unlink( $target );  
    }
}
?>