ftp_nlist

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_nlist -- Возвращает список файлов в заданной директории

Описание

array ftp_nlist ( resource ftp_stream, string directory )

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

ftp_stream

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

directory

Имя директории для получения списка файлов. Этот параметр также может включать аргументы, например ftp_nlist($conn_id, "-la /your/dir"); Обратите внимание, что этот параметр не проходит экранирование спецсимволов, так что могут возникнуть проблемы с именами, содержащими пробелы и прочие подобные символы.

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

Возвращает массив имён файлов в директории или FALSE при возникновении ошибки.

Примеры

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

<?php

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

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

// получить содержимое текущей директории
$contents = ftp_nlist($conn_id, ".");

// вывод $contents
var_dump($contents);

?>

Приведенный выше пример выведет :

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

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

ftp_rawlist()



ftp_nlist
mail at martinauer dot net
14-May-2006 10:27
Beware:
The array will contain complete paths, not just filenames. At least in PHP 4.3.11 when I tried

ftp_nlist("www.example.com/docs/some/thing")

it dumped something like this:

  [0]=>
  string(41) "www.example.com/docs/some/thing/file1.htm"
  [1]=>
  string(41) "www.example.com/docs/some/thing/file2.htm"
  [2]=>
  string(41) "www.example.com/docs/some/thing/file3.htm"
  [3]=>
  string(41) "www.example.com/docs/some/thing/file4.htm"
  [4]=>
  string(41) "www.example.com/docs/some/thing/file5.htm"
franck569 at free dot fr
24-Feb-2006 10:32
better version of turigeza on yahoo com ftp_rmdirr() function.

This return true or false if the path will be removed :

function ftp_rmdirr($handle, $path)
{
   if(!@ftp_delete($handle, $path))
   {
       $list = @ftp_nlist($handle, $path);
       if(!empty($list))
           foreach($list as $value)
               ftp_rmdirr($handle, $value);
   }
  
   if(@ftp_rmdir($handle, $path))
       return true;
   else
       return false;
}
turigeza on yahoo com
07-Nov-2005 07:10
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);
   }
?>
It would be very useful if it was built into php. After all most of the time we want to remove non empty directories too. I bet everyone out there dealing with the file system had faced this problem.
dreamsavior at gmail dot com
29-Jun-2005 09:19
Here is the function that would checking whether the given path is directory or not, using ftp_nlist;

<?php
function is_ftp_dir($itempath, $ftp_server, $ftp_user_name='anonymous', $ftp_user_pass='') {
   if (empty(
$ftp_user_name)) {
      
$ftp_user_name = "anonymous";
   }
   if (
$itempath[0]!=="/") {
      
$itempath = "/".$itempath;
   }

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

  
$contents = ftp_nlist($conn_id, "$itempath");

   if (!empty(
$contents[0])) {
      
$check = str_replace($itempath, "", $contents[0]);
       if (!empty(
$check)) {
           return
true;
       }
   }
  
ftp_close($conn_id);
}

// example :
  
if (is_ftp_dir("/pub/ftp/unknownitem", "ftp.nowhere", 'username', 'verysecret'')) {
       // do something related to directory handling action
   } else {
       // The target item is a file ...
   }

?>
ds at over dot hu
18-Dec-2004 08:43
Another file filecollect script, with static.

<?php

function filecollect($conn_id,$dir='.') {
  static
$flist=array();
  if (
$files = ftp_nlist($cid,$dir)){
   foreach (
$files as $file) {
     if (
ftp_size($cid, $file) == "-1"){
      
filecollect($cid,$file);
     } else
$flist[] = $file;
   }
  }
  return
$flist;
}

$conn_id = ftp_connect('ftp.nowhere.com') or die("Couldn't connect to server");
  if (@
ftp_login($conn_id, 'anonymous', 'pass@nowhere.com')){
  
$filelist = filecollect($conn_id);
   echo
"<pre>";
    
print_r($filelist);
   echo
"</pre>";
  }

?>
webmaster at torbox dot info
26-Sep-2004 09:16
To use custom LIST - flags, for example
LIST -aF ../*/
(listing protected pub dirs)
You can use
<?php
$list
= ftp_nlist($ftp, "-aF ../*/");
?>
Took me a while to clever that one out :-)
micksam7 at neodecoder dot com
29-Feb-2004 02:40
A little correction to king_killa at juggalos4life dot com's note, it isn't ftp_res, it's ftp_size.

By the way, here is a complete function that will get all the files on a server, then write them to a array.

<?php
$ftp1
= ftp_connect('ftp.nowhere1230404.foo') or die("Couldn't connect to server");
ftp_login($ftp1,'foo','bar');
ftp_pasv($ftp1, TRUE); //Passive Mode is better for this

//Get them file!
echo "Collecting Files on Neodecoder<br>";
//Set defaults just in case. PHP complains anyway if we don't.
$dir = "";

function
filecollect($dir,$filelist) {
global
$ftp1; //Get our ftp
$files = ftp_nlist($ftp1,$dir); //get files in directory
foreach ($files as $file) {
 
$isfile = ftp_size($ftp1, $file);
 if(
$isfile == "-1") { //Is a file or directory?
 
$filelist = filecollect($dir.'/'.$file,$filelist,$num); //If a folder, do a filecollect on it
 
}
 else {
 
$filelist[(count($filelist)+1)] = $file; //If not, add it as a file to the file list
 
}
}
return
$filelist;
}

$filelist = filecollect($dir,$filelist);

echo
"<pre>";
print_r($filelist);
echo
"</pre>";
?>

This is really handy if your trying to transfer all the files from a ftp server to another server. Which, is why I made the script in the first place. heh..
tobrien at florahill dot vic dot edu dot au
13-Oct-2003 08:27
ftp_nlist() or ftp_rawlist() takes ages then returns nothing...

If you are having this issue, you may need to enable PASV mode FTP transfers using the ftp_pasv() function.

Example...

<?php
$ftp_host
= "yourFTPHost";
$ftp_user = "yourUsername";
$ftp_password = "yourPassword";

//Connect
echo "<br />Connecting to $ftp_host via FTP...";
$conn = ftp_connect($ftp_host);
$login = ftp_login($conn, $ftp_user, $ftp_password);

//
//Enable PASV ( Note: must be done after ftp_login() )
//
$mode = ftp_pasv($conn, TRUE);

//Login OK ?
if ((!$conn) || (!$login) || (!$mode)) {
   die(
"FTP connection has failed !");
}
echo
"<br />Login Ok.<br />";

//
//Now run ftp_nlist()
//
$file_list = ftp_nlist($conn, "");
foreach (
$file_list as $file)
{
  echo
"<br>$file";
}

//close
ftp_close($conn);

?>
aRc
14-Jul-2003 12:46
in windows, ftp_nlist will die on a directory with a space in it's name.  to get around this, use ftp_chdir:

//change directory
ftp_chdir($conn, "directory with spaces");
//then blindly list
$contents = ftp_nlist($conn, "");
neodeus at allesamarsch dot com
03-Jun-2003 10:10
This is an Example tp read out a Complete FTP Server ( beginn at your root dir )
   function files($dir)
   {
       /*
       if(!isset($dir) || empty($dir))
       {
           $dir=ftp_pwd($this->conn_id);
       }
       */
       unset($list);
       unset($files);
       unset($folders);
       unset($folder);
       unset($file);
       @ftp_chdir($this->conn_id, $dir);
       $dir = ftp_pwd($this->conn_id);
       $list=Array();
       $list=ftp_nlist($this->conn_id, "$dir");
       $files = Array();
       $folders = Array();
       for($i = 0; $i != sizeof($list); $i++)
       {
           $entry = str_replace("//", "", $list[$i]);
           if(@ftp_chdir($this->conn_id, $entry))
           {
               $folders[] = $entry;
               ftp_chdir($this->conn_id, $dir);
           }
           else
           {
               $files[] = $entry;
           }
       }
       print "\t<b> Dateien in ".$dir." :</b><br><br>";
       foreach($files as $file)
       {
           print $file."<br>";
       }
       print "\t<b>Ordner in ".$dir." :</b> <br><br>";
       foreach ($folders as $folder)
       {
           print "\t".$folder."<br>";
           ftp_chdir($this->conn_id, $dir);
           $this->files($folder);
       }
   }
louis at ewens dot com
29-Apr-2003 04:03
If you do a wildcard or other search for a particular file and the file doesn't exist, Solaris FTP servers send back "search*.xml: No such file or directory" as a single element in the response array. This makes it hard to check for the presence of a file.

One possible work-around is to parse your own raw directory listing. Or you could check for the error verbatim. But different servers could return different values. A simpler way to compensate is to use the ftp_size command to validate the returned file:

if ( ($filelist = ftp_nlist( $this->conn_id, $filesearch )) === FALSE )
{
       Error( "Could not get file list" );
       return FALSE;
}
// File actually exists? Catches invalid FTP server list responses
if ( !count($filelist) || ftp_size( $this->conn_id, $filelist[0] ) == -1 )
{
       Error( "No valid files" );
       return FALSE;
}
// File is really there, fetch it or whatever else you want to do
rfr at ajato dot com dot br
12-Feb-2003 08:25
There are some FTP servers that just dont accept the ftp_nlist command, they return a bool variable. but I think all of them accept the LIST command which is the ftp_rawlist command. So yu have to parse rawlist to nlist. I found a code here posted by "fredrik" but it shows a bug if the files at the ftp server have spaces oon theeir name... so here its a better function:
function rawlist_2_nlist($list)
{
   $newlist = array();
   reset($list);
   while (list(,$row) = each($list))
   {
       $buf="";
       if ($row[0]=='d'||$row[0]=='-'){
       $buf = substr($row,55);
       $newlist[]=$buf;
       }
   }

return $newlist;
}
ryan at wonko dot com
20-Mar-2002 07:31
A note to developers using PHP on Windows servers: as of PHP 4.1.2, ftp_nlist() is broken in the Windows build of PHP. It will return nothing at all, even if the same code works fine on UNIX. So if you're going crazy trying to figure out why the function isn't returning anything, stop wasting your time, you're not doing anything wrong. Hopefully this will get fixed in future versions, although it's apparently been an issue since at least 4.0.6.

More info on this bug is at http://bugs.php.net/bug.php?id=16057
markw at altexa dot com
13-Nov-2000 12:33
You can do a wildcard file listing with ftp_nlist, as in:

$list=ftp_nlist($conn_id, "$dir/*.txt");

<ftp_nb_putftp_pasv>
 Last updated: Tue, 15 Nov 2005