PDA

View Full Version : Removing all files in a folder


[m] at
06-02-2005, 07:14 PM
I have a script for admins of our site to upload new skins. When the script is executed, it makes a directory, and then moves the files to the directory as they're checked and uploaded. However, if even one of the files doesn't pass the checks (not the right file size, not the right dimensions) the script stops to prevent wonky skins from being uploaded.

When the script detects an error, I'd like it to also delete the files that have been uploaded and delete the directory that was created so that the user won't run into any problems when they try again. Does anyone know how I can do this?

marek_mar
06-02-2005, 08:53 PM
Try this:

<?php
$dir = 'path/to/dir';
$d = dir($dir);
while (false !== ($entry = $d->read())) {
unlink($entry);
}
$d->close();
rmdir($dir);
?>
Added missing semicolon

Kurashu
06-02-2005, 09:23 PM
That's a mighty helpful snipplet.

*saves*

EDIT: You need to add a semi-colon to the rmdir function. >_>

EDIT 2: <_< After doing some searching on php.net I found this in the rmdir comments:

<?php
function delete_files($target, $exceptions, $output=true)
{
$sourcedir = opendir($target);
while(false !== ($filename = readdir($sourcedir)))
{
if(!in_array($filename, $exceptions))
{
if($output)
{ echo "Processing: ".$target."/".$filename."<br>"; }
if(is_dir($target."/".$filename))
{
// recurse subdirectory; call of function recursive
delete_files($target."/".$filename, $exceptions);
}
else if(is_file($target."/".$filename))
{
// unlink file
unlink($target."/".$filename);
}
}
}
closedir($sourcedir);
if(rmdir($target))
{ return true; }
else
{ return false; }
}

//example
$exceptions = array(".", "..");
if(delete_files("/var/www/html/this_dir", $exceptions, true))
{ echo "deletion successed"; }
else
{ echo "deletion failed"; }
?>

anshul
06-03-2005, 09:04 AM
Indeed a nice script :thumbsup:

Can you tell a script/snippet for a script to copy a directory entirely or calculate total size of a directory. Special thanks.http://www.mediasworks.com/script/

[m] at
06-06-2005, 02:53 PM
Thanks =)