Tuesday, July 10, 2007

PHP Recursive Function to create a directory

Apparently, in PHP versions less than 5.0, you can't recursively create a directory. Here's a little function I wrote to allow this...works on *nix systems:


<?
// set the number of recursions, so we don't get out of control w/ infinite recursions
// like when we don't have file system access to create directories
// or when we try to create a directory w/ incorrect characters in it...like an asterisk (for example)
$num_recursions = 0;

// recursive function to create a directory
function mkdir_recursive($dir)
{
global $num_recursions;
$num_recursions++;

echo "attempting to create $dir\n";
$dir_res = @mkdir($dir);

if ($num_recursions > 100)
{
echo "Cannot create $dir...num_recursions in mkdir_recursive = $num_recursions\n";
exit;
}

if ($dir_res === false)
{
$next_attempt_dir = substr($dir, 0, strrpos(substr($dir, 0, -1), '/'));
echo "dir creation failed...Now attempting to create $next_attempt_dir\n";
mkdir_recursive($next_attempt_dir);

echo "trying again to create $dir\n";
$dir_res = mkdir($dir);
}
else // dir creation successful. Reset the global recursion counter.
{
$num_recursions = 0;
}

}
?>

No comments: