Get All Files in Directory and All Child Directories

PHP walk recursively with iterator over all directories and filesI was playing with PHP the other day and was trying to fetch and rename 1000s of files I have stored locally on my machine. Seemingly PHP isn’t the best language to that operation Python or even BASH could do the job though it was nice to give it a try. So this is what I came up, simple and straightforward.

<?php

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($files as $file) {
    $fileNewName = $file . '_' . time();
    rename($file, $fileNewName);
}

Though the example above may create slightly unexpected results, it could for example rename current directory and we don’t want that. We should add some extra configuration parameters so we select just files that should be renamed by passing: RecursiveDirectoryIterator::SKIP_DOTS to skip all “.” and “..”. After that is done we need to set the correct order of processing the files which could be useful if we have nested directory structure: RecursiveIteratorIterator::SELF_FIRST this is setting parent files/dirs to be first.

Lastly we should make sure that directories or files which are with restricted permissions should be skipped to do that pass: RecursiveIteratorIterator::CATCH_GET_CHILD. Here is the final example:

<?php

$files = new RecursiveIteratorIterator(
	new RecursiveDirectoryIterator('.', RecursiveDirectoryIterator::SKIP_DOTS),
    	RecursiveIteratorIterator::SELF_FIRST, 
	RecursiveIteratorIterator::CATCH_GET_CHILD
)
foreach($files as $file) {
	if (!$file->isDir()) {
    		$fileNewName = $file . '_' . time();
    		rename($file, $fileNewName);
	}
}
It's only fair to share...Buffer this pageShare on Facebook0Tweet about this on TwitterShare on Google+0Share on LinkedIn2Share on Reddit0Pin on Pinterest0Email this to someone
About

Just a guy with strong interest in PHP and Web technologies

Posted in PHP, Small Tips Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*