Ultimate Web Tips
your Wordpress, jQuery, PHP, MySQL, Linux and CSS guide to a successful website
Read more:

March 17th, 2011

Get all files recursive with RecursiveIteratorIterator

PHP, by Joakim Ling.

There is a lot of ways to do this, but using the PHP5 built in SPL RecursiveIteratorIterator makes it simple to get them all in one go.

Recently I was hosting one of my projects on a web-hotel where I couldn’t figure out how to change file permissions on uploaded files from the browser. The issue was that the files was set to apache as owner/group and my FTP user had no write access with apache as group. To quickly get around this I wrote a PHP script that changed the user to my FTP user to gain full access.

Here is how to get a list of all files recursive:

<?php
$dir = dirname(__FILE__) . '/';
 
try {
	$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveIteratorIterator::LEAVES_ONLY));
	foreach( $it as $fullFileName => $fileSPLObject )
		print $fullFileName . " " . $fileSPLObject->getFilename() . "\n";
}
catch (UnexpectedValueException $e) {
	printf("Directory [%s] contained a directory we can not recurse into", $dir);
}
?>

and this is how you change owner:

<?php
// change owner to "webuser"
chown($filepath, "webuser");
 
// to verify
$stat = stat($filepath);
var_dump(posix_getpwuid($stat['uid']));
?>

Interactive PHP

Learn interactive PHP click here to find out more

Back Top

Club World Casinos