Jump to content

Delete files from directory / sub-directory


skwap

Recommended Posts

i have made an delete files script which works for only one directory but not sub directory so i want to delete files of same extention from directory and subdirectory.

 

My current code is

 


<?

$dir = 'hmm/';

function scanr($dir){

$arr = glob($dir.'/*.jpg');
foreach($arr as $vv){



//check if $vv is a file
if(is_file($vv)){

//if file, get the filename
$vx=explode('/',$vv);
$file=$vx[count($vx)-1];


// if no extension delete the file
unlink($vv);
// print the deletion message
echo $vv." deleted!<br>";}else{
// if $vv is a dir then scan it again for files
scanr($vv);
}}
}

scanr($dir);
?>

Link to comment
Share on other sites

This will do what you want:

 

<?php

$dir = 'del_contents';
$ext = 'jpg';

recursiveDeletion( $dir, $ext );

function recursiveDeletion( $dir, $ext )
{
$directoryResource = opendir( $dir );
while( false !== ( $fs = readdir( $directoryResource ) ) )
{
	if( in_array( $fs, array( '.', '..' ) ) )
		continue;

	$file = sprintf( '%s/%s', $dir, $fs );
	if( is_dir( $file ) )
		recursiveDeletion( $file, $ext );
	else
		if( preg_match( sprintf( '/^.*\.%s$/', $ext ), $file ) )
			printf( "File %s has %sbeen deleted.\n", 
				$file, ( @unlink( $file ) ) ? '' : 'not ' );
    }
closedir($directoryResource);
}

 

It will delete everything in a directory and all its sub directories.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.