<abbr title="PHP: Hypertext Preprocessor">PHP</abbr>: <abbr title="File Transfer Protocol">FTP</abbr> Recursive rm

As a contributor of Webmasters-fr.net couldn’t make his recursive FTP rm work, I began to look at the examples provided in the PHP manual… I couldn’t make them work either.

That’s why I ended up rewriting the ftp_rmAll, and it now works fine on my FTP server. I still have to play around to make sure it does work in any situation, but here is the code:


function ftp_rmAll($conn_id,$dst_dir){ if (!@ftp_chdir($conn_id, $dst_dir)) { die(“Couldn’t change directoryn”); } $ar_files = ftp_nlist($conn_id, “”); if (is_array($ar_files)){ // makes sure there are files for ($i=0;$i < sizeof($ar_files);$i++){ // for each file $st_file = $ar_files[$i]; // don’t care about . and .. if ($st_file != ‘.’ && $st_file != ‘..’) // check if it is a directory if (ftp_size($conn_id, $st_file) == -1){ ftp_rmAll($conn_id, $st_file); // if so, use recursion } else { ftp_delete($conn_id, $st_file); // if not, delete the file } } }

ftp_rmdir($conn_id, $dst_dir); // delete empty directories }

$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

ftp_rmAll($conn_id, “/repertoire”);

 
---

Commenting is closed for this article.

---