Return to Snippet

Revision: 12343
at March 11, 2009 15:21 by fackz


Initial Code
<?php

# server credentials
$host = "ftp server";
$user = "username";
$pass = "password";

# connect to ftp server
$handle = @ftp_connect($host) or die("Could not connect to {$host}");

# login using credentials
@ftp_login($handle, $user, $pass) or die("Could not login to {$host}");

function recursiveDelete($directory)
{
    # here we attempt to delete the file/directory
    if( !(@ftp_rmdir($handle, $directory) || @ftp_delete($handle, $directory)) )
    {
        # if the attempt to delete fails, get the file listing
        $filelist = @ftp_nlist($handle, $directory);

        # loop through the file list and recursively delete the FILE in the list
        foreach($filelist as $file)
        {
            recursiveDelete($file);
        }

        #if the file list is empty, delete the DIRECTORY we passed
        recursiveDelete($directory);
    }
}
?>

Initial URL
http://jrtashjian.com/2008/08/27/code-snippet-recursive-delete-with-ftp-2/

Initial Description
A recursive function is a function that has the ability to call itself (recursion). I ran into this problem while trying to delete a directory containing files and/or other directories. I was using FTP at the time so, the function will be written as such. It can be easily ported to using filesystem functions by following the same logic/flow.

Initial Title
Recursive Delete with FTP

Initial Tags

                                

Initial Language
PHP