百科狗-知识改变命运!
--

ftp_rawlist() - ftp函数

梵高12个月前 (11-21)阅读数 11#技术干货
文章标签数组

ftp_rawlist()

(PHP 4, PHP 5, PHP 7)

返回指定目录下文件的详细列表

说明

ftp_rawlist(resource $ftp_stream,string $directory): array

ftp_rawlist()函数将执行 FTP LIST命令,并把结果做为一个数组返回。

参数

$ftp_stream

FTP 连接资源。

$directory

目录路径。

$recursive

如果此参数为TRUE,实际执行的命令将会为LIST -R

返回值

ftp_rawlist() - ftp函数

返回一个数组,数组的每个元素为返回文本的每一行,输出结构不会被解析。使用函数ftp_systype()可以用来判断 FTP 服务器的类型,从而可以用来判断返回列表的类型。

范例

ftp_rawlist()例子

以上例程的输出类似于:

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"
}

更新日志

版本说明
4.3.0增加$recursive参数。

参见

  • ftp_nlist()返回给定目录的文件列表
Here's a simple function that'll parse the data returned by ftp_rawlist() into an associative array. I wrote it because some of the functions listed below are way to long, complex or won't work with file names that contain spaces. 
All parse_rawlist Functions here have one Problem.
when a file starts with a space character like " robots.txt ", it will be ignored.
Rename, delete will fail...
With this handy function based on functions presented here you get the file list in alphabetical order with all directories on top: 
In case anybody wants to get a detailed listing using the MLSD command over a passive connection, the following function might be helpful as a starting point for your own implementation:

Please note that this function ignores the setting of ftp_pasv(). Making the function to work universally for both active and passive connections is left as an exercise to the reader ;-)
Get a listing of all files including hidden files except '.' or '..' use:

This had me dancing in circles for some time!
Note that this function also will return false if the content of the provided directory is empty.
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);
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: 
There are a couple of php-related reasons given here for ftp_rawlist returning an empty result. However be aware that ZoneAlarm (and possibly other) firewalls can block responses without giving any visible clue so be sure to check that first.
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
ftp_rawlist kept returning empty file listing, it would work on some machines but not others, it turned out to be ftp_pasv command was needed.
Very frustrating
this is function to check for dirs 
To format the _recrusive_ result of this function I use this: 
Please pay attention that ftp_rawlist() function returns empty result if there is a folder with space. You must backslash it with addcslashes() function.
IMPORTANT: at the same time any other function like ftp_delete() or ftp_rmdir() in opposite, will not be able to delete file/folder if folder name with space will be backslashes http://proxy-list.org/
The solution of fredvanetten at tinqle dot com is nice but needs further evaluation as because of the preg_split and static listing of the variables will produce different values: comparing a file of today or an older, from a previous year:
Array
(
  [time] => 2012
  [day] => 11
  [month] => Sep
  [size] => 37262
  [group] => group
  [user] => owner
  [number] => 1
  [rights] => -rw-rw-rw-
)
Array
(
  [time] => 14:01
  [day] => 23
  [month] => Apr
  [size] => 37262
  [group] => group
  [user] => owner
  [number] => 1
  [rights] => -rw-rw-rw-
)
Why not using POSIX regex to do the job here ? A preg_replace returns the information in an associative array with the following keys:







 * that's a bonus: it will tell you if the item is either a file or a directory
Code is shown below:
$list=@ftp_rawlist($con,$directory) ;
$items=array() ;
foreach($list as $_)
preg_replace(
'`^(.{10}+)(\s*)(\d{1})(\s*)(\d*|\w*)'.
'(\s*)(\d*|\w*)(\s*)(\d*)\s'.
'([a-zA-Z]{3}+)(\s*)([0-9]{1,2}+)'.
'(\s*)([0-9]{2}+):([0-9]{2}+)(\s*)(.*)$`Ue',
'$items[]=array(
"rights"=>"$1", 
"number"=>"$3", 
"owner"=>"$5", "group"=>"$7",
"file_size"=>"$9",
"mod_time"=>"$10 $12 $14:$15",
"file"=>"$17",
"type"=>print_r((preg_match("/^d/","$1"))?"dir":"file",1));',
$_) ; # :p
Some FTP servers only allow you to get list of files under current working directory. So if you always get result as empty array (array(0){ }), try changing the cwd befor get the list: 
On my PC (XP and Apache installed) - ftp_rawlist (with Parameter true) does only print a folder list - no subfolders, no files.
So i created this recursive function that writes all filenames (incl. paths) to a array. I tested it on Mac, Linux and Windows - it works (as long as you don't use folders with spaces...).
If you need more information: feel free to set more split[x]-Options and write them to the $files-array.

Ueli, Zurich
hope this helps someone: 
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;
}
Your code is ok, just replace $i = 0 instead of 1
Thank you 
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: 
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"); }
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 '
'; 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 ''; print ""; // name of file print ""; // date info // prep size $size = $clean[4]; $size = $size / 1000; $size = ceil($size); if ($size = 1000) { $measure = "MB"; $size = $size / 1000; } else { $measure = "K"; } print ""; // size echo ''; // link to delete file echo ''; } // end if } // end foreach loop 1 echo '
$clean[8]$clean[5] $clean[6] $clean[7]$size $measure'; print ""; echo 'DELETE
';
Excelent expresion, but don't match SUID, SGUI and Sticky flags when 'x' is disabled. Fix it with [rwxstST-]. 
list all (including hidden files and dirs):

just as ftp command:
LIST al 
"-aF " is equal to '-al', please refer to "ls --help"
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 
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 
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.
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 
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:

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
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. 
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 : 
I'm afraid I forgot the "parsenext" function in my previous note. Here it is: 
This script will properly handle FTP servers where the returned date/time differs from the generic mm-dd-YYYY hh:mm:ss format:

This script works fine on any raw list that complies with the following format:
permissions number owner group size time name [" -> " link_to]
where time may have whatever format the FTP server wants. ;-)
It also returns folders, files and links in separated sorted lists (got this idea from the note of "postmaster at alishomepage dot com" in this help page).
I fixed jmv AT jmvware DOT com's script: 
If you write

The command will be "LIST -a", so the retuned list will also contain hidden files like ".htaccess".
In this case all files and folders of the current directory are contained.
To list another folder, you must change to it with "ftp_chdir".
Here we go for a 100% working code... :D

so this will simply "get" all the information WITHOUT being in any case interfered with some spaces, ... etc etc... It will even put files in a $files array and folders in a $folders array, and sort them, so you will be able of using all this later
and: the "folders" will NOT contain "." and ".." ;)
so you can use all this to make a beautiful FTP interface... later on you could for example put permissions and etc etc in other arrays to use them in your result... cute....
Another "formula" for decoding the rawlist: the ide is that normaly a "ls" contains info like below:
      
and: the "time" contains a ":" (which is NOT contained in any of the other infos -if we reversely read the array)
and, in the case the "time" would not exist, i have done a "protection script" that would try to find out using the year... Yet that may NOT always work since a user name or group name MAY contain an item like "1999" etc... (and i did not check the date format reversely -on the filename first- since a probability of presence is higher of a date is MUCH higher in a filename)
So here we go:

and $elmt would *normally* contain the info we want... but i'm still working on it!

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)