tags:

views:

74

answers:

2

Hi, I have a main directory like :

/import/

and in /import/ i have lots of sub directories, containing audio files.

I would like to create a php script to move all the audio files from the sub directories into the main directory.

Thanks guys :)

+2  A: 
$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("/import/"));

$it->rewind();
while($it->valid()) {
    $full_path = $it->key();
    $relative_path = $it->getSubPath();
    if ($it->getDepth() > 0 && preg_match("/regex/", $relative_path)) [
        //move stuff
    }
    $it->next();
}

See RecursiveIteratorIterator and RecursiveDirectoryIterator. You could also encapsulate the iterator in a RegexIterator.

Artefacto
Nice solution, you made me discover something awesome today. Thank you.
0plus1
+1 for using Spl, -1 for overcomplicating it's usage. Basically, all he needs is `foreach($it as $path => $file) { // move $path to target dir}` - no need for regex or getDepth or something. Just use the absolute paths.
Gordon
@Gordon So where are my 8 reputation points? :p
Artefacto
@Gordon I'm assuming he has other things there besides audio files, which he doesn't want to move
Artefacto
@Artefacto might be, but then he could still just use the absolute paths as well as just strpos for the right extension or fnmatch or use a FilterIterator or detect the mimetype (which would make sure it really is an audiofile). Also, I think LEAVES_ONLY is the default, so you can leave *pun* that out.
Gordon
@Gordon Well, I think by this time I've been brainwashed and think regexes are the simpler solution. Well, they often aren't, but they are more the most general solution, so I tend to forget everything else.
Artefacto
@Gordon Yes, you're right, it seems to be the default; I'll remove it.
Artefacto
@Artefacto Regex are the devil's right hand ;)
Gordon
@Gordon, and SPL is his left. :-)
salathe
@salathe so we're doomed :D
Gordon
+1  A: 

Have a look at opendir(), is_dir(), copy() and unlink().

What you need to do is:

Open the /import directory and iterate through the listing.

For each entry, if it's a directory (and not . or ..), get the listing of that sub directory.

Then for each audio file in that sub directory, copy to /import/, then use unlink to delete.

Pete