Library FTP : Delete recursively directory with function delete_dir()
Hello
I am trying to use the FTP library and the delete_dir function. But impossible to delete if a folder contains sub-folders. I'm using the 3.1.11 version.
I looked at the function in question and I have a question. (line 474 in library FTP.php)
public function delete_dir($filepath)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
// Add a trailing slash to the file path if needed
$filepath = preg_replace('/(.+?)\/*$/', '\\1/', $filepath);
$list = $this->list_files($filepath);
if ( ! empty($list))
{
for ($i = 0, $c = count($list); $i < $c; $i++)
{
// If we can't delete the item it's probably a directory,
// so we'll recursively call delete_dir()
if ( ! preg_match('#/\.\.?$#', $list[$i]) && ! @ftp_delete($this->conn_id, $list[$i]))
{
$this->delete_dir($filepath.$list[$i]);
}
}
}
if (@ftp_rmdir($this->conn_id, $filepath) === FALSE)
{
if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_delete');
}
return FALSE;
}
return TRUE;
}
If we look at line 491, we try to delete the folder with ftp_delete And if it returns false, it calls the delete_dir () function again on line 493. Why is it also passing the $ filepath with the $ list [$ i]? As a result, the path cannot be good since we just concatenate it with the initial path!
I tried an example with this structure :
dir1
dir1-2
file1.txt
file2.txt
dir1-3
1st loop : filepath = dir1/ 2nd loop : filepath = dir1/dir1/dir1-2/ (ERROR, it duplicates the initial directory ! ) 3rd loop : filepath = dir1/dir1/dir1-3/ (ERROR, it duplicates the initial directory ! )
I hope to have been clear
Pierre
PS: Sorry for my english, I'm french :)
It's assuming $list[$i] doesn't contain the full path ... Honestly, the documentation on ftp_nlist() is horrible and I have no idea if it's supposed to do that or not.
Looks like you might be right and I can't test it propertly myself, so you're welcome to submit a pull request.