1

I would like to list all my folder on my web application without the files in it. At the moment I'm using this code but this will give me all files and folders:

//Connect
$conn = ftp_connect($ftp_server);
$login = ftp_login($conn, $ftp_username, $ftp_userpassword);

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

$file_list = ftp_nlist($conn, "/webspace/httpdocs/brentstevens.nl/u_media/$uid/");

foreach ($file_list as $file)
{
    // process folder
}

But this will output all files and folders. How can I adjust this code to only serve the folders?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Brent Stevens
  • 23
  • 1
  • 4

3 Answers3

2

If your server supports MLSD command and you have PHP 7.2 or newer, you can use ftp_mlsd function:

$files = ftp_mlsd($conn, $path);

foreach ($files as $file)
{ 
    if ($file["type"] == "dir")
    {
        echo $file["name"]."\n";
    }
} 

If you do not have PHP 7.2, you can try to implement the MLSD command on your own. For a start, see user comment of the ftp_rawlist command:
https://www.php.net/manual/en/function.ftp-rawlist.php#101071


It is not easy to implement this without MLSD in a way that works for any FTP server. See also Check if FTP entry is file or folder with PHP.

But if you need to work against one specific FTP server only, you can use ftp_rawlist to retrieve a file listing in a platform-specific format and parse that.

The following code assumes a common *nix format.

$lines = ftp_rawlist($conn, $path);

foreach ($lines as $line)
{
    $tokens = explode(" ", $line);
    $name = $tokens[count($tokens) - 1];
    $type = $tokens[0][0];

    if ($type == 'd')
    {
        echo "$name\n";
    }
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

If your server not supports MLSD command or you have PHP <7.2 and ftp_rawlist marks directory as <DIR>

function getList($connection, string $path): array
{
    $rawlist = ftp_rawlist($connection, $path) ?: [];

    $items = [];
    foreach ($rawlist as $data) {
        $item = array_combine(['date', 'time', 'size', 'name'], preg_split('/\s/', $data, -1, PREG_SPLIT_NO_EMPTY));
        $item['type'] = $item['size'] === '<DIR>' ? 'dir' : 'file';
        $item['size'] = (int)$item['size'];

        $items[] = $item;
    }

    return $items;
}

function getFileList($connection, string $path): array
{
    return array_values(array_filter(getList($connection, $path), function ($file) { return $file['type'] === 'file'; }));
}

function getDirList($connection, string $path): array
{
    return array_values(array_filter(getList($connection, $path), function ($file) { return $file['type'] === 'dir'; }));
}
0

You have to use http://php.net/manual/en/function.ftp-rawlist.php function and with regular expression parse type which in your case is letter d