Posted By

fackz on 03/11/09


Tagged

delete recursive FTP


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

jamesming
fackz
BrianCoyDesign


Recursive Delete with FTP


 / Published in: PHP
 

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

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.

  1. <?php
  2.  
  3. # server credentials
  4. $host = "ftp server";
  5. $user = "username";
  6. $pass = "password";
  7.  
  8. # connect to ftp server
  9. $handle = @ftp_connect($host) or die("Could not connect to {$host}");
  10.  
  11. # login using credentials
  12. @ftp_login($handle, $user, $pass) or die("Could not login to {$host}");
  13.  
  14. function recursiveDelete($directory)
  15. {
  16. # here we attempt to delete the file/directory
  17. if( !(@ftp_rmdir($handle, $directory) || @ftp_delete($handle, $directory)) )
  18. {
  19. # if the attempt to delete fails, get the file listing
  20. $filelist = @ftp_nlist($handle, $directory);
  21.  
  22. # loop through the file list and recursively delete the FILE in the list
  23. foreach($filelist as $file)
  24. {
  25. recursiveDelete($file);
  26. }
  27.  
  28. #if the file list is empty, delete the DIRECTORY we passed
  29. recursiveDelete($directory);
  30. }
  31. }
  32. ?>

Report this snippet  

You need to login to post a comment.