PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ftp_set_option> <ftp_rename
Last updated: Fri, 05 Sep 2008

view this page in

ftp_rmdir

(PHP 4, PHP 5)

ftp_rmdirУдаляет директорию

Описание

bool ftp_rmdir ( resource $ftp_stream , string $directory )

Удаляет директорию directory .

Список параметров

ftp_stream

Идентификатор соединения с FTP сервером

directory

Имя директории. Должен содержать относительный или абсолютный путь к пустой директории

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования ftp_rmdir()

<?php

$dir 
'www/';

// установка соединения
$conn_id ftp_connect($ftp_server);

// проверка имени пользователя и пароля
$login_result ftp_login($conn_id$ftp_user_name$ftp_user_pass);

// попытка удаления директории $dir
if (ftp_rmdir($conn_id$dir)) {
    echo 
"Директория $dir удалена\n";
} else {
    echo 
"Не удалось удалить директорию $dir\n";
}

ftp_close($conn_id);

?>

Смотрите также



ftp_set_option> <ftp_rename
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
ftp_rmdir
romain
06-Mar-2008 01:16
I noticed 2 small mistakes in the code proposed by TSE_Webdesign... and added an error message.

if ( empty($nlist) ) { ==> if ( empty($list) ) {

and

DeleteDirRecursive($item); ==> DeleteDirRecursive($resource, $item);

So here is a correct version...

    /**
     *    Delete the provided directory and all its contents from the FTP-server.
     *
     *    @param string $path            Path to the directory on the FTP-server relative to the current working directory
     */
function DeleteDirRecursive($resource, $path) {
    $result_message = "";
    $list = ftp_nlist ($resource, $path);
    if ( empty($list) ) {
        $list = RawlistToNlist( ftp_rawlist($resource, $path), $path . ( substr($path, strlen($path) - 1, 1) == "/" ? "" : "/" ) );
    }
    if ($list[0] != $path) {
        $path .= ( substr($path, strlen($path)-1, 1) == "/" ? "" : "/" );
        foreach ($list as $item) {
        if ($item != $path.".." && $item != $path.".") {
            $result_message .= DeleteDirRecursive($resource, $item);
        }
        }
        if (ftp_rmdir ($resource, $path)) {
            $result_message .= "Successfully deleted $path <br />\n";
        } else {
            $result_message .= "There was a problem while deleting $path <br />\n";
        }
    }
    else {
        if (ftp_delete ($resource, $path)) {
            $result_message .= "Successfully deleted $path <br />\n";
        } else {
            $result_message .= "There was a problem while deleting $path <br />\n";
        }
    }
    return $result_message;
}

     /**
     *    Convert a result from ftp_rawlist() to a result of ftp_nlist()
     *
     *    @param array $rawlist        Result from ftp_rawlist();
     *    @param string $path            Path to the directory on the FTP-server relative to the current working directory
     *    @return array                An array with the paths of the files in the directory
     */
function RawlistToNlist($rawlist, $path) {
    $array = array();
    foreach ($rawlist as $item) {
        $filename = trim(substr($item, 55, strlen($item) - 55));
        if ($filename != "." || $filename != "..") {
        $array[] = $path . $filename;
        }
    }
    return $array;
}
TSE-WebDesign
11-Nov-2006 11:47
The problem with the previous posts about recursive deleting of directories is that you might need to set error_reporting(0), but this doesn't work always.
When you've got your own error_handler set, you'll notice that an error is thrown even when setting error_reporting(0).

The following script generates various errors:
<?php
function ftp_rmdirr($path, $handle)
   {
   if (!(@
ftp_rmdir($handle, $path) || @ftp_delete($handle, $path)))
       {
      
$list = ftp_nlist($handle, $path);
       if (!empty(
$list))
           foreach(
$list as $value)
              
ftp_rmdirr($value, $handle);
       }
   @
ftp_rmdir($handle, $path);
   }
?>

Let me explain: with the @-sign you can suppres the error generated if the command failed, but somehow it still outputs the error.
So the easiest solution for this is to check if the path is to a file or a directory, which you can check with ftp_nlist or ftp_rawlist.
ftp_nlist(filename) returns the filename, ftp_nlist(dirname) returns a list with the files in that directory, or returns an empty array if the directory is empty.
If ftp_nlist is not working, you can use ftp_rawlist() and parse the results.
With ftp_rawlist(resource, path) you can get a detailed list of the files in a specific directory. At the end of every element of the array that ftp_rawlist(resource, path) returns, you'll find the filename or the dirname.
This file- or dirname you can precede with the path you've provided for ftp_rawlist(), which gives you the ability to check if a path to a file or directory is really a file or a directory.

This is what I came up with:
<?
   
/**
     *    Delete the provided directory and all its contents from the FTP-server.
     *
     *    @param string $path            Path to the directory on the FTP-server relative to the current working directory
     */
   
function DeleteDirRecursive ($resource, $path)
    {
       
$list = ftp_nlist ($resource, $path);
        if ( empty(
$nlist) ){
           
$list = RawlistToNlist ( ftp_rawlist($resource, $path), $path . ( substr($path, strlen($path) - 1, 1) == "/" ? "" : "/" ) );
        }
        if (
$list[0] != $path){
           
$path .= ( substr($path, strlen($path)-1, 1) == "/" ? "" : "/" );
            foreach (
$list as $item){
                if (
$item != $path.".." && $item != $path."."){
                   
DeleteDirRecursive ($item);
                }
            }
           
ftp_rmdir ($resource, $path);
        }
        else {
           
ftp_delete ($resource, $path);
        }
    }
   
   
/**
     *    Convert a result from ftp_rawlist() to a result of ftp_nlist()
     *
     *    @param array $rawlist        Result from ftp_rawlist();
     *    @param string $path            Path to the directory on the FTP-server relative to the current working directory
     *    @return array                An array with the paths of the files in the directory
     */
   
function RawlistToNlist ($rawlist, $path)
    {
       
$array = array();
        foreach (
$rawlist as $item){
           
$filename = trim(substr($item, 55, strlen($item) - 55));
            if (
$filename != "." || $filename != ".."){
               
$array[] = $path . $filename;
            }
        }
        return
$array;
    }
?>
mail at martinauer dot net
14-May-2006 07:36
At least in PHP 4.3.11 ftp_nlist lists complete paths, not just filenames. Therefore the function by uma at di4 dot com did not work for me. But it worked with a small change in line 6 like this:

function ftp_rmAll($conn_id,$dst_dir){
   $ar_files = ftp_nlist($conn_id, $dst_dir);
   //var_dump($ar_files);
   if (is_array($ar_files)){ // makes sure there are files
       for ($i=0;$i<sizeof($ar_files);$i++){ // for each file
           $st_file = basename($ar_files[$i]);
           if($st_file == '.' || $st_file == '..') continue;
           if (ftp_size($conn_id, $dst_dir.'/'.$st_file) == -1){ // check if it is a directory
               ftp_rmAll($conn_id,  $dst_dir.'/'.$st_file); // if so, use recursion
           } else {
               ftp_delete($conn_id,  $dst_dir.'/'.$st_file); // if not, delete the file
           }
       }
   }
   $flag = ftp_rmdir($conn_id, $dst_dir); // delete empty directories
   //return $flag;
}
uma at di4 dot com
07-Mar-2006 01:06
Removing a directory using FTP(modified Version):
___________________________________________

function ftp_rmAll($conn_id,$dst_dir){
    $ar_files = ftp_nlist($conn_id, $dst_dir);
    //var_dump($ar_files);
    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];
            if($st_file == '.' || $st_file == '..') continue;
            if (ftp_size($conn_id, $dst_dir.'/'.$st_file) == -1){ // check if it is a directory
                ftp_rmAll($conn_id,  $dst_dir.'/'.$st_file); // if so, use recursion
            } else {
                ftp_delete($conn_id,  $dst_dir.'/'.$st_file); // if not, delete the file
            }
        }
    }
    $flag = ftp_rmdir($conn_id, $dst_dir); // delete empty directories
    //return $flag;
}
mvh at list dot ru
02-Mar-2006 02:02
to: turigeza on yahoo com
You have made a mistake in the function. In it parts:
<?php
foreach($list as $value)
   
ftp_rmdirr($value, $handle);
?>

Need:
<?php
foreach($list as $value)
{
    if (
$value != $path . '/.' && $value != $path . '/..')
       
ftp_rmdirr($value, $handle);
}
?>
mgyth_at-online_dot-no
24-Feb-2006 08:19
Worth beeing aware of:
ftp_rmdir scrips that are porly written and require you to supply a $dir to delete, may in some cases, where the $dir is empty, run the script on the your base dir on the server, thus deleting all the files you have ftp acces to.
turigeza on yahoo com
07-Nov-2005 04:15
Recursive directory delete using ftp_nlist() ...
<?php
function ftp_rmdirr($path, $handle)
    {
    if (!(@
ftp_rmdir($handle, $path) || @ftp_delete($handle, $path)))
        {
       
$list = ftp_nlist($handle, $path);
        if (!empty(
$list))
            foreach(
$list as $value)
               
ftp_rmdirr($value, $handle);
        }
    @
ftp_rmdir($handle, $path);
    }
?>
aidan at php dot net
29-Jul-2005 11:28
If you wish to recursively delete a directory and all its contents, see the below function.

http://aidanlister.com/repos/v/function.ftp_rmdirr.php

ftp_set_option> <ftp_rename
Last updated: Fri, 05 Sep 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites