Harley1979 Posted August 21, 2007 Share Posted August 21, 2007 Does anyone know how to detect a folders contents with PHP and delete all files within? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/65960-solved-remove-folder-contents/ Share on other sites More sharing options...
MadTechie Posted August 21, 2007 Share Posted August 21, 2007 <?php function full_rmdir( $dir ) { if ( !is_writable( $dir ) ) { if ( !@chmod( $dir, 0777 ) ) { return FALSE; } } $d = dir( $dir ); while ( FALSE !== ( $entry = $d->read() ) ) { if ( $entry == '.' || $entry == '..' ) { continue; } $entry = $dir . '/' . $entry; if ( is_dir( $entry ) ) { if ( !$this->full_rmdir( $entry ) ) { return FALSE; } continue; } if ( !@unlink( $entry ) ) { $d->close(); return FALSE; } } $d->close(); rmdir( $dir ); return TRUE; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/65960-solved-remove-folder-contents/#findComment-329794 Share on other sites More sharing options...
Wuhtzu Posted August 21, 2007 Share Posted August 21, 2007 Like you said you have to detect every single file and delete them one by one.... Take a good look at these functions: http://no.php.net/opendir http://no.php.net/readdir http://no.php.net/unlink As the example in readdir() you simply loop over all the files and each time you have a file you use unlink() to delete it. EDIT: Or just use the code MadTechie posted - it's about perfect. Because there is alot more to it than taking one file and deleting it - what if it's an directory and you need to delete all that directories files before you can delete the dir ect. Quote Link to comment https://forums.phpfreaks.com/topic/65960-solved-remove-folder-contents/#findComment-329797 Share on other sites More sharing options...
MadTechie Posted August 21, 2007 Share Posted August 21, 2007 note: remove the rmdir( $dir ); at the end of the code if you wish to keep the folder itself but remove the files inside Quote Link to comment https://forums.phpfreaks.com/topic/65960-solved-remove-folder-contents/#findComment-329802 Share on other sites More sharing options...
Harley1979 Posted August 21, 2007 Author Share Posted August 21, 2007 Thanks guys, you're a great help! That did the trick! Quote Link to comment https://forums.phpfreaks.com/topic/65960-solved-remove-folder-contents/#findComment-329883 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.