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

search for in the

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

view this page in

ftp_rawlist

(PHP 4, PHP 5)

ftp_rawlistReturns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource $ftp_stream , string $directory [, bool $recursive ] )

ftp_rawlist() executes the FTP LIST command, and returns the result as an array.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory path.

recursive

If set to TRUE, the issued command will be LIST -R.

Return Values

Returns an array where each element corresponds to one line of text.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Examples

Example #1 ftp_rawlist() example

<?php

// set up basic connection
$conn_id ftp_connect($ftp_server);

// login with username and password
$login_result ftp_login($conn_id$ftp_user_name$ftp_user_pass);

// get the file list for /
$buff ftp_rawlist($conn_id'/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

ChangeLog

Version Description
4.3.0 recursive was added.

See Also



ftp_rename> <ftp_raw
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
ftp_rawlist
paul maybe at squirrel mail org
24-Apr-2008 03:13
Regarding converting permissions from symbolic notation to octal, note that Hazem dot Khaled at gmail dot com's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
Mike TUMS
31-Mar-2008 10:53
Response to Hazem Khaled's get_size function.
You missed kilobytes.
<?php
function get_size($size)
     {
         if (
$size < 1024)
          {
              return
round($size,2).' Byte';
          }
         elseif (
$size < (1024*1024))
          {
              return
round(($size/1024),2).' Kb';
          }
         elseif (
$size < (1024*1024*1024))
          {
              return
round((($size/1024)/1024),2).' Mb';
          }
         elseif (
$size < (1024*1024*1024*1024))
          {
              return
round(((($size/1024)/1024)/1024),2).' Gb';
          }
          elseif (
$size < (1024*1024*1024*1024*1024))
          {
              return
round((((($size/1024)/1024)/1024)/1024),2).' Tb';
          }
    }
?>
weltvolk
04-Jan-2008 04:17
With this handy function based on functions presented here you get the file list in alphabetical order with all directories on top:

<?php
function rawlist_dump() {
  global
$ftp_connect;
 
$ftp_rawlist = ftp_rawlist($ftp_connect, ".");
  foreach (
$ftp_rawlist as $v) {
   
$info = array();
   
$vinfo = preg_split("/[\s]+/", $v, 9);
    if (
$vinfo[0] !== "total") {
     
$info['chmod'] = $vinfo[0];
     
$info['num'] = $vinfo[1];
     
$info['owner'] = $vinfo[2];
     
$info['group'] = $vinfo[3];
     
$info['size'] = $vinfo[4];
     
$info['month'] = $vinfo[5];
     
$info['day'] = $vinfo[6];
     
$info['time'] = $vinfo[7];
     
$info['name'] = $vinfo[8];
     
$rawlist[$info['name']] = $info;
    }
  }
 
$dir = array();
 
$file = array();
  foreach (
$rawlist as $k => $v) {
    if (
$v['chmod']{0} == "d") {
     
$dir[$k] = $v;
    } elseif (
$v['chmod']{0} == "-") {
     
$file[$k] = $v;
    }
  }
  foreach (
$dir as $dirname => $dirinfo) {
      echo
"[ $dirname ] " . $dirinfo['chmod'] . " | " . $dirinfo['owner'] . " | " . $dirinfo['group'] . " | " . $dirinfo['month'] . " " . $dirinfo['day'] . " " . $dirinfo['time'] . "<br>";
  }
  foreach (
$file as $filename => $fileinfo) {
      echo
"$filename " . $fileinfo['chmod'] . " | " . $fileinfo['owner'] . " | " . $fileinfo['group'] . " | " . $fileinfo['size'] . " Byte | " . $fileinfo['month'] . " " . $fileinfo['day'] . " " . $fileinfo['time'] . "<br>";
  }
}
rawlist_dump();
?>
reg (russia, vladimir)
02-Jul-2007 03:11
i'v wrote "php ftp recursive" function, you can use in any purposes you like. finally you will get an array of: 1) additional information like time an file's count 2) all files with extensions you defined with paths of course. the function is workable.

$values = array(
                         "sitename" => "abc.ru",
                         "ftpserver" => "u12345.ftp.masterhost.ru",
                         "ftpuser" => "u12345",
                         "ftppassword" => "mypassword",
                         "remotedir" => "abc.ru/www"
                        );
function getAllFilesViaFTP($values){
    $beginTime = time();
    echo "connecting to ".$values['sitename']."\n";
    // set up a connection or die
    if (!$conn_id = ftp_connect($values['ftpserver'])) return ("can't connect to ".$values['ftpserver']."\n");
    // try to login
    if (!@ftp_login($conn_id, $values['ftpuser'], $values['ftppassword'])) echo "can't login to ".$values['sitename']." with entered ".$ftp_user." and password(...) \n";
    // get the file list for $values['remotedir']
    $fileList = ftp_rawlist($conn_id, $values['remotedir'], TRUE);
    // print_r($fileList);
    $fileList_c = count($fileList);
    $allFiles = $allFilesCount = $allUseFulFilesCount = null;
    $currentDir = $values['remotedir'];
    for ($i=0;$i<$fileList_c;$i++){
        // change current dir, if current array element is an empty line
        if (!$fileList[$i]) $currentDir = $fileList[$i+1];
        else{
            $allFilesCount++;
            $fileInfo = list() = explode(" ", $fileList[$i]);
            // print_r($fileInfo);
            $fileName = $fileInfo[count($fileInfo) - 1];
            if (preg_match("/\.php/", $fileName) or preg_match("/\.htm/", $fileName) or preg_match("/\.html/", $fileName)){
                $allUseFulFilesCount++;
                $allFiles[] = preg_replace("/:/", "", $currentDir)."/".$fileName;
            }
        }
    }
    // close the connection
    ftp_close($conn_id);
    // time
    $fullTime = time() - $beginTime;
    $result = array (
                            "allFilesCount" => $allFilesCount,
                            "allUseFulFilesCount" => $allUseFulFilesCount,
                            "fullTime" => $fullTime,
                            "fileList" => $allFiles
                            );
    return $result;
}

$fileList = getAllFilesViaFTP($values);
print_r($fileList);
Hazem dot Khaled at gmail dot com
22-Nov-2006 11:25
that comment have 4 function
the 1st function "<b>get_files</b>" get the list of files by the full bath "/www/ex/"
and return 3 arrays
dir = the directories in this directory with the time ,date ,more ...
linke = the links in this directory with the time ,date ,more ...
file = the files in this directory with the time ,date ,more ...

the 2nd function "chmodnum" convert from "drwxrwxrwx" to "777"
* i found it in php.net manual

the 3rd function "get_size" convert from the byte to MB or GB or TB

the 4th function "get_type" return if this file or directory or link

the functions
<?php
   
function get_files($path = '')
     {
         if (
$path == '' && !$_GET['path'])
          {
            
$path = '/';
          }
         elseif (
$path == '')
          {
            
$path = $_GET['path'];
          }
   
        
       
//$all_folders = ftp_nlist($this->conection, $_GET['path']);
       
$array = ftp_rawlist($this->conection, $path);
        if (
is_array($array))
        foreach (
$array as $folder)
         {
           
$struc = array();
           
$current = preg_split("/[\s]+/",$folder,9);
           
           
$struc['perms']    = $current[0];
           
$struc['permsn']= chmodnum($current[0]);
           
$struc['number']= $current[1];
           
$struc['owner']    = $current[2];
           
$struc['group']    = $current[3];
           
$struc['size']    = get_size($current[4]);
           
$struc['month']    = $current[5];
           
$struc['day']    = $current[6];
           
$struc['time']    = $current[7];
           
$struc['name']    = str_replace('//','',$current[8]);
           
//$struc['raw']    = $folder;
           
           
if ($struc['name'] != '.' && $struc['name'] != '..' && get_type($struc['perms']) == "folder")
             {
               
$folders[] = $struc;
             }
            elseif (
$struc['name'] != '.' && $struc['name'] != '..' && get_type($struc['perms']) == "link")
             {
               
$links[] = $struc;
             }
            elseif (
$struc['name'] != '.' && $struc['name'] != '..')
             {
               
$files[] = $struc;
             }
         }
        return array(
$folders,$links,$files);
     }

    function
chmodnum($mode) {
      
$realmode = "";
      
$legal =  array("","w","r","x","-");
      
$attarray = preg_split("//",$mode);
       for(
$i=0;$i<count($attarray);$i++){
           if(
$key = array_search($attarray[$i],$legal)){
              
$realmode .= $legal[$key];
           }
       }
      
$mode = str_pad($realmode,9,'-');
      
$trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
      
$mode = strtr($mode,$trans);
      
$newmode = '';
      
$newmode .= $mode[0]+$mode[1]+$mode[2];
      
$newmode .= $mode[3]+$mode[4]+$mode[5];
      
$newmode .= $mode[6]+$mode[7]+$mode[8];
       return
$newmode;
    }
    function
get_size($size)
     {
         if (
$size < 1024)
          {
              return
round($size,2).' Byte';
          }
         elseif (
$size < (1024*1024))
          {
              return
round(($size/1024),2).' MB';
          }
         elseif (
$size < (1024*1024*1024))
          {
              return
round((($size/1024)/1024),2).' GB';
          }
         elseif (
$size < (1024*1024*1024*1024))
          {
              return
round(((($size/1024)/1024)/1024),2).' TB';
          }
     }

    function
get_type($perms)
     {
        if (
substr($perms, 0, 1) == "d")
         {
            return
'folder';
         }
        elseif (
substr($perms, 0, 1) == "l")
         {
            return
'link';
         }
        else
         {
            return
'file';
         }
     }
?>
ari at bs-inc dot com
17-Oct-2006 11:24
This is a little cleaner:

function parse_rawlist( $array )
{
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']  = $current[0];
        $struc['number'] = $current[1];
        $struc['owner']  = $current[2];
        $struc['group']  = $current[3];
        $struc['size']  = $current[4];
        $struc['month']  = $current[5];
        $struc['day']    = $current[6];
        $struc['time']  = $current[7];
        $struc['year']  = $current[8];
        $struc['raw']  = $curraw;
        $structure[$struc['name']] = $struc;
    }
   return $structure;

}
kerbpm
15-Sep-2006 12:31
Your code is ok, just replace $i = 0 instead of 1
Thank you

<?php

function parse_rawlist( $array ) {

   for (
$i = 1; $i < count($array); $i++ ) {

      
$current = $array[$i];
  
      
$structure[$i]['perms']  = substr($current, 0, 10);
      
$structure[$i]['number'] = trim(substr($current, 11, 3));
      
$structure[$i]['owner']  = trim(substr($current, 15, 8));
      
$structure[$i]['group']  = trim(substr($current, 24, 8));
      
$structure[$i]['size']  = trim(substr($current, 33, 8));
      
$structure[$i]['month']  = trim(substr($current, 42, 3));
      
$structure[$i]['day']    = trim(substr($current, 46, 2));
      
$structure[$i]['time']  = substr($current, 49, 5);
      
$structure[$i]['name']  = substr($current, 55, strlen($current) - 55);

   }

   return
$structure;

}

?>
MSpreij at GMail
10-Sep-2006 03:11
The following was inspired by a few others here, ofcourse ;-)
Works for filenames with spaces (leading, trailing, consecutive and what not), formats the date a little taking year/time into account, leaves out items not in the $filetypes array below, and returns a nice nested assoc array:

<?php

$filetypes
= array('-'=>'file', 'd'=>'directory', 'l'=>'link');

$c = ftp_connect('localhost');
ftp_login($c, 'jackcrow', 'banshee');
$data = ftp_rawlist($c, '/users/jackcrow');

foreach(
$data as $line) {
    if (
substr(strtolower($line), 0, 5) == 'total') continue; # first line, skip it
   
preg_match('/'. str_repeat('([^\s]+)\s+', 7) .'([^\s]+) (.*)/', $line, $matches); # Here be Dragons
   
list($permissions, $children, $owner, $group, $size, $month, $day, $time, $name) = array_slice($matches, 1);
   
# if it's not a file, directory or link, I don't really care to know about it :-) comment out the next line if you do
   
if (! in_array($permissions[0], array_keys($filetypes))) continue;
   
$type = $filetypes[$permissions[0]];
   
$date = date('d/m/y H:i', (strpos($time, ':') ? mktime(substr($time, 0, 2), substr($time, -2), 0, $month, $day) : mktime(0,0,0,$month, $day, $time) ) );
   
$files[$name] = array('type'=>$type, 'permissions'=>substr($permissions, 1), 'children'=>$children, 'owner'=>$owner, 'group'=>$group, 'size'=>$size, 'date'=>$date);
}

print_r($files);

?>

(I'm using a pretty simple regex pattern (non-space-stuff, whitespace, non-space-stuff etc), but amazingly /it still works!/ K.I.S.S.! The time part in the pattern is done separately to make sure only 1 space is taken out before the filename, which might start with spaces for all you know)
admin at mikeholloway dot co dot uk
04-Dec-2005 12:38
I was having problems picking up the directories on a mac using cjacobsen at pge dot cl's (11-Jan-05) solution. Slight ammendment to the regexp works for me:

ereg("([-dl][rwxstST-]+).* ?([0-9 ]* )?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)
d dot lloyd at tnw dot tudelft dot nl
27-Sep-2005 04:22
One comment regaring the method tig3r uses to determine the listing type.

Windows servers can return a listing in unix format if the ftp server has been told to use unix formatting. The only robust solution I have is to try both ereg commands once and see which one successfully returns an array.
tig3r at poczta dot onet dot pl
18-Aug-2005 01:31
Previous example (by davidknoll at o2 dot co dot uk) works well if ftp_systype() returned "UNIX", but sometimes I am experiencing "Windows_NT". Here is some improvement:

<?php
function parsed_listing($path)
{
  
$conn = ftp_connect(FTP_HOST);
  
ftp_login($conn, FTP_USER, FTP_PASS);
  
$systype = ftp_systype($conn_id);
  
$list = ftp_rawlist($conn, "-a ".FTP_BASE.$path);
  
ftp_close($conn);
  
$i = 0;

   foreach (
$list as $current) {
      switch (
$systype) {
         case
"Windows_NT":
        
ereg("([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)",$current,$split);
         if (
is_array($split)) {
            if (
$split[3]<70) { $split[3]+=2000; } else { $split[3]+=1900; } // 4digit year fix
           
$parsed[$i]['isdir'] = ($split[7]=="<DIR>");
           
$parsed[$i]['size'] = $split[7];
           
$parsed[$i]['month'] = $split[1];
           
$parsed[$i]['day'] = $split[2];
           
$parsed[$i]['time/year'] = $split[3];
           
$parsed[$i]['name'] = $split[8];
           
$i++;
         }
         break;

         case
"UNIX":
         default:

// etc.

        
break;
      }
   }
   return
$parsed;
}
?>
davidknoll at o2 dot co dot uk
14-Jul-2005 02:00
Well, this works for me:

<?php
function parsed_listing($path)
{
   
$conn = ftp_connect(FTP_HOST);
   
ftp_login($conn, FTP_USER, FTP_PASS);
   
$list = ftp_rawlist($conn, "-a ".FTP_BASE.$path);
   
ftp_close($conn);
   
$i = 0;
    foreach (
$list as $current) {
       
$split = preg_split("[ ]", $current, 9, PREG_SPLIT_NO_EMPTY);
        if (
$split[0] != "total") {
           
$parsed[$i]['isdir']        = $split[0]{0} === "d";
           
$parsed[$i]['perms']        = $split[0];
           
$parsed[$i]['number']    = $split[1];
           
$parsed[$i]['owner']        = $split[2];
           
$parsed[$i]['group']        = $split[3];
           
$parsed[$i]['size']        = $split[4];
           
$parsed[$i]['month']        = $split[5];
           
$parsed[$i]['day']        = $split[6];
           
$parsed[$i]['time/year']    = $split[7];
           
$parsed[$i]['name']        = $split[8];
           
$i++;
        }
    }
    return
$parsed;
}
?>
nate at 8networks dot com
07-May-2005 10:41
this snip fixes the date problem with the listing and sorts out the variables:

$filedata['access_permissions']
$filedata['link_count']
$filedata['uid']
$filedata['gid']
$filedata['size']
$filedata['mod_date_month']
$filedata['mod_date_day']
$filedata['mod_time']
$filedata['name']

list($filedata['access_permissions'], $filedata['link_count'], $filedata['uid'], $filedata['gid'], $filedata['size'], $filedata['mod_date_month'], $filedata['mod_date_day'], $filedata['mod_time'], $filedata['name']) = preg_split("/[\s,]+/", $value);

$filedata['type'] = $filedata['access_permissions']{0};

$filedata['access_permissions'] = substr($filedata['access_permissions'],1);

// now check the date to see if the last modifcation was this year or last.

if ( strrpos($filedata['mod_time'], ':') != 2 ) { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . $filedata['mod_time']; $filedata['mod_time'] = "00:00"; } else { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . date("Y"); }
john at nm-design dot com
29-Apr-2005 08:14
I'm not a traditional programmer, so I often take a different approach then most programmers. Here's how I get file information from an FTP file list. It's very simple (which I like). Comments are welcome:

    // make your FTP connection calls here, then ...   
    $contents = ftp_rawlist($ftp_id, ".");
   
    echo '<TABLE>';
   
    foreach ($contents as $key => $value) {
   
        $info = explode(" ", $value);
        $clean = array();
        foreach ($info as $key => $value) {
            if (!empty($value)) { $clean[] = $value; }
        } // end foreach loop 2
       
        if ( ($clean[8] != ".") AND ($clean[8] != "..") AND ($clean[8] != "html") AND ($clean[8] != "logs") AND ($clean[8] != "protected") AND ($clean[8] != "sys") ) {
            echo '<TR>';
            print "<TD WIDTH=\"40%\">$clean[8]</TD>"; // name of file
            print "<TD WIDTH=\"20%\" ALIGN=\"CENTER\">$clean[5] $clean[6] $clean[7]</TD>"; // date info
            // prep size
            $size = $clean[4];
            $size = $size / 1000; $size = ceil($size); if ($size <= 0) { $size = 1; }
            if ($size >= 1000) { $measure = "MB"; $size = $size /  1000; } else { $measure = "K"; }
            print "<TD WIDTH=\"20%\" ALIGN=\"CENTER\">$size $measure</TD>"; // size
            echo '<TD WIDTH="20%" ALIGN="CENTER" BGCOLOR="#FFFFE6" CLASS="bodyBold">'; print "<A HREF=\"$PHP_SELF?Submit=DELETE&file=$clean[8]\">"; echo 'DELETE</A></TD>'; // link to delete file
            echo '</TR>';
        } // end if
       
    } // end foreach loop 1
   
    echo '</TABLE>';
marc dot peterlongo at francetelecom dot com
03-Feb-2005 12:57
When you try:

$path = "directory pathname with spaces";
$list = ftp_rawlist($conn_id,$path);

It doesn't work

but when you try:

$path = "directory pathname with spaces";
ftp_chdir($conn_id,$path);
$list = ftp_rawlist($conn_id,".");

It works
cjacobsen at pge dot cl
11-Jan-2005 03:44
Excelent expresion, but don't match SUID, SGUI and Sticky flags when 'x' is disabled. Fix it with [rwxstST-].

<?php

function itemize_dir($contents) {
   foreach (
$contents as $file) {
       if(
ereg("([-dl][rwxstST-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
          
$type = (int) strpos("-dl", $regs[1]{0});
          
$tmp_array['line'] = $regs[0];
          
$tmp_array['type'] = $type;
          
$tmp_array['rights'] = $regs[1];
          
$tmp_array['number'] = $regs[2];
          
$tmp_array['user'] = $regs[3];
          
$tmp_array['group'] = $regs[4];
          
$tmp_array['size'] = $regs[5];
          
$tmp_array['date'] = date("m-d",strtotime($regs[6]));
          
$tmp_array['time'] = $regs[7];
          
$tmp_array['name'] = $regs[9];
       }
      
$dir_list[] = $tmp_array;
   }
   return
$dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
greg at upsdn dot net
20-Dec-2004 09:58
list all (including hidden files and dirs):
<?php
  $contents
= ftp_rawlist($conn_id, "-al ".$dir_name);
?>

just as ftp command:
LIST al

"-aF " is equal to '-al', please refer to "ls --help"
greg at upsdn dot net
26-Nov-2004 08:55
The previous regular expression(by Jonathan Almarez,ergye at yahoo dot com and guru at virusas dot lt) is very good.But i found it does not  take into account for directories(number>9)

Change [0-9] to [0-9]*

The code below not only parses:
drwxrwxr-x     9 msik     ia           4096 Nov  5 14:19 Group3

It also parses:
drwxrwxr-x   19 msik     ia           4096 Nov  5 14:19 Group3
3
drwxrwxr-x   119 msik     ia           4096 Nov  5 14:19 Group3
3

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach (
$contents as $file) {
       if(
ereg("([-dl][rwxst-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
          
$type = (int) strpos("-dl", $regs[1]{0});
          
$tmp_array['line'] = $regs[0];
          
$tmp_array['type'] = $type;
          
$tmp_array['rights'] = $regs[1];
          
$tmp_array['number'] = $regs[2];
          
$tmp_array['user'] = $regs[3];
          
$tmp_array['group'] = $regs[4];
          
$tmp_array['size'] = $regs[5];
          
$tmp_array['date'] = date("m-d",strtotime($regs[6]));
          
$tmp_array['time'] = $regs[7];
          
$tmp_array['name'] = $regs[9];
       }
      
$dir_list[] = $tmp_array;
   }
   return
$dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
Jonathan Almarez
25-Nov-2004 01:16
To make the latest correction to the parsing code:

"ergye at yahoo dot com" dosen't take into account for files or directories that are older than a year where instead of showing the time, it shows the year.

The code below not only parses:
drwxrwxr-x   2 503      503          4096 Dec  3 12:12 CVAR

It also parses:
drwxrwxr-x   2 503      503          4096 Dec  3  2003 CVAR

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach (
$contents as $file) {
       if(
ereg("([-dl][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
          
$type = (int) strpos("-dl", $regs[1]{0});
          
$tmp_array['line'] = $regs[0];
          
$tmp_array['type'] = $type;
          
$tmp_array['rights'] = $regs[1];
          
$tmp_array['number'] = $regs[2];
          
$tmp_array['user'] = $regs[3];
          
$tmp_array['group'] = $regs[4];
          
$tmp_array['size'] = $regs[5];
          
$tmp_array['date'] = date("m-d",strtotime($regs[6]));
          
$tmp_array['time'] = $regs[7];
          
$tmp_array['name'] = $regs[9];
       }
      
$dir_list[] = $tmp_array;
   }
   return
$dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
23-Oct-2004 05:53
Note that there is no standard for the format, therefore don't be suprised when parsing routines for this work perfectly on some servers, and fail horribly on some.
ergye at yahoo dot com
30-Sep-2004 07:52
The previous regular expression is super, but does not take simlinks into account. Change [-d] to [-dl] and instead of indicating directories we should indicate the type of the items:

0 = file
1 = directory
2 = simlink

<?php

function itemize_dir($contents) {
    foreach (
$contents as $file) {
        if(
ereg("([-dl][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)) {
           
$type = (int) strpos("-dl", $regs[1]{0});
           
$tmp_array['line'] = $regs[0];
           
$tmp_array['type'] = $type;
           
$tmp_array['rights'] = $regs[1];
           
$tmp_array['number'] = $regs[2];
           
$tmp_array['user'] = $regs[3];
           
$tmp_array['group'] = $regs[4];
           
$tmp_array['size'] = $regs[5];
           
$tmp_array['date'] = date("m-d",strtotime($regs[6]));
           
$tmp_array['time'] = $regs[7];
           
$tmp_array['name'] = $regs[8];
        }
       
$dir_list[] = $tmp_array;
    }
    return
$dir_list;
}

$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
guru at virusas dot lt
03-Sep-2004 01:31
Lets say only one of these scripts can accept filenames with spaces, but that script doesn't return all info that we may need, so i have modified a little bit one of my script and added some more regexp from here:

<?

$buff = ftp_rawlist($cid,"/");
foreach ($buff as $file)
{
      if(ereg("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)",$file,$regs))
    { 
        if(substr($regs[1],0,1)=="d") $isdir=1; else $isdir=0;
        $tmp_array['line']=$regs[0];
        $tmp_array['isdir']=$isdir;
        $tmp_array['rights']=$regs[1];
        $tmp_array['number']=$regs[2];
        $tmp_array['user']=$regs[3];
        $tmp_array['group']=$regs[4];
        $tmp_array['size']=$regs[5];
        $tmp_array['date']=date("m-d",strtotime($regs[6]));
        $tmp_array['time']=$regs[7];
        $tmp_array['name']=$regs[8];
     }
    $dir_list[]=$tmp_array;
}

?>

The result is smth like that:

  8 =>
    array
      'line' => '-rw-r--r--   1 guru     users           4 Sep  3 09:41 testas testas testas.txt'
      'isdir' => 0
      'rights' => '-rw-r--r--'
      'number' => '1'
      'user' => 'guru'
      'group' => 'users'
      'size' => '4'
      'date' => '09-03'
      'time' => '09:41'
      'name' => 'testas testas testas.txt'
  9 =>
    array
      'line' => 'drwxr-xr-x   3 guru     users        4096 Aug 20 08:54 upload'
      'isdir' => 1
      'rights' => 'drwxr-xr-x'
      'number' => '3'
      'user' => 'guru'
      'group' => 'users'
      'size' => '4096'
      'date' => '08-20'
      'time' => '08:54'
      'name' => 'upload'

Home this will help someone
eros at speedy dot com dot ar
02-Sep-2004 12:06
NO, NO, NO.

The above examples are all wrong, the spaces given in array are not there "just because", its just a tabbed structure. In php we don't have structures like in c/cpp, but the following function will do the job.

<?php

function parse_rawlist( $array ) {

    for (
$i = 1; $i < count($array); $i++ ) {

       
$current = $array[$i];
   
       
$structure[$i]['perms']  = substr($current, 0, 10);
       
$structure[$i]['number'] = trim(substr($current, 11, 3));
       
$structure[$i]['owner']  = trim(substr($current, 15, 8));
       
$structure[$i]['group']  = trim(substr($current, 24, 8));
       
$structure[$i]['size']   = trim(substr($current, 33, 8));
       
$structure[$i]['month']  = trim(substr($current, 42, 3));
       
$structure[$i]['day']    = trim(substr($current, 46, 2));
       
$structure[$i]['time']   = substr($current, 49, 5);
       
$structure[$i]['name']   = substr($current, 55, strlen($current) - 55);

    }

    return
$structure;

}

?>
soon7 at wanadoo dot fr
15-Jul-2004 12:17
Hi all !
ther is a litlle mistake in the naivesong 's message .
Indeed , you stop to parse too early ...
I tried and fix it like this :
<?
// getting the list
  $list = ftp_rawlist ($ftp_stream, $ftp_directory);
   $folders = array();
   $files = array();
   $links = array();
   for ($i=0; $i<count($list); $i++)
   {
        //----convert tabs to blanks
        //----delete multiple blanks
// Here begin my modifications
list ($permissions, $list[$i]) = parsenext ($list[$i]);
     list ($number, $list[$i]) = parsenext ($list[$i]);
     list ($owner, $list[$i]) = parsenext ($list[$i]);
     list ($group, $list[$i]) = parsenext ($list[$i]);
     list ($size, $list[$i]) = parsenext ($list[$i]);
     list ($timeMonth,$list[$i]) = parsenext ($list[$i]);
     list ($timeDay,$list[$i]) = parsenext ($list[$i]);
     list ($timeTime,$list[$i]) = parsenext ($list[$i]);
     $filename=$list[$i];
// by taking $filename in last position , it works even if there is some space in its name
//then we put it in the m array with the new things
//----ok, put all this into the related array
if ($filename != "." && $filename != "..")
     {
       $m = array();
       $m["name"] = $filename;
       $m["link"] = $filelink;
       $m["size"] = afficherPoidsFichier($size);
       $m["month"] = $timeMonth;
       $m["day"] = $timeDay;
       $m["time"] = $timeTim