Recursive FTP Make Directory (mkdir)
Posted on 14th May 2009 by SameerManaging files over ftp using PHP can be a pain. One of the problems is dealing with long paths that may or may not exist. Fortunately, you can create functions to ease the problems.
For example, using php’s built-in ftp_mkdir function, to create the directory “/hello/kitty” you must first create the directory “/hello” and then “/hello/kitty”. Wouldn’t it be easier to have a helper function that could be passed the full path of the final directory that you want created (”/hello/kitty”) and it would take care of creating each directory in the path by itself?
Here is the code to do it:
// recursive make directory function for ftp
function make_directory($ftp_stream, $dir)
{
// if directory already exists or can be immediately created return true
if (ftp_is_dir($ftp_stream, $dir) || @ftp_mkdir($ftp_stream, $dir)) return true;
// otherwise recursively try to make the directory
if (!make_directory($ftp_stream, dirname($dir))) return false;
// final step to create the directory
return ftp_mkdir($ftp_stream, $dir);
}
function ftp_is_dir($ftp_stream, $dir)
{
// get current directory
$original_directory = ftp_pwd($ftp_stream);
// test if you can change directory to $dir
// suppress errors in case $dir is not a file or not a directory
if ( @ftp_chdir( $ftp_stream, $dir ) ) {
// If it is a directory, then change the directory back to the original directory
ftp_chdir( $ftp_stream, $original_directory );
return true;
} else {
return false;
}
}
Your code is really nice. Its helpful and almost ready to copy paste and use.
Thanks !

