Create missing directories before performing ftp_put

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
TipPro
Forum Commoner
Posts: 35
Joined: Wed Mar 15, 2006 6:39 pm

Create missing directories before performing ftp_put

Post by TipPro »

This is a function I wrote to create directories that do not exist before I perform a ftp_put. Is this already built into PHP or is there a better way of going about this? Thanks!

Code: Select all

//example usage...
$file = "temp123/temp456/temp789/myfile.txt";
checkforAndMakeDirs($ftp_con, $file);
ftp_put($ftp_con, $file);

function checkForAndMakeDirs($connection, $file) {
        $origin = ftp_pwd($connection);
        $parts = explode("/", dirname($file);

        foreach ($parts as $curDir) {
            // Attempt to change directory, suppress errors
            if (@ftp_chdir($connection, $curDir) === false) {
                ftp_mkdir($connection, $curDir); //directory doesn't exist - so make it
                ftp_chdir($connection, $curDir); //go into the new directory
            }
        }

        //go back to the origin directory
        ftp_chdir($connection, $origin);
}
Post Reply