Current Location: Home> Latest Articles> ftp_rawlist Method to get recursive directory structure

ftp_rawlist Method to get recursive directory structure

gitbox 2025-05-26

In the process of operating FTP using PHP, we often encounter situations where we need to obtain a directory and all its subdirectories and files on the remote server. Although methods such as ftp_nlist and ftp_rawlist are provided in PHP's FTP extension, they only list the contents of the current directory by default. If we want to recursively obtain the complete directory structure, we need to manually implement logical processing. This article will use a complete example to analyze in detail how to use ftp_rawlist to implement recursive acquisition of directory structures on FTP.

Basic knowledge review: ftp_rawlist

ftp_rawlist is a function in PHP that obtains a detailed file list of specified directories on the FTP server. Its return result is similar to the format output of UNIX's ls -l command. For example:

 Array
(
    [0] => drwxr-xr-x   2 ftp      ftp          4096 Jan 01 12:00 folder
    [1] => -rw-r--r--   1 ftp      ftp          1234 Jan 01 12:01 file.txt
)

We can parse the file type (directory or file), name, size, modification time and other information from this information.

Implementation ideas

To implement recursive acquisition of directory structure, we need:

  1. Use ftp_rawlist to get all entries in the current directory;

  2. Analyze the return content of each item and identify whether it is a directory or a file;

  3. If it is a directory (and not . or ... ), then recursively enter the directory;

  4. Build the directory structure into a tree array for easy subsequent processing or display.

Complete sample code

Here is a available PHP example that demonstrates how to implement it:

 <?php

function getRecursiveFtpList($ftpConn, $path)
{
    $structure = [];
    $rawList = ftp_rawlist($ftpConn, $path);

    if ($rawList === false) {
        return $structure;
    }

    foreach ($rawList as $line) {
        $parts = preg_split("/\s+/", $line, 9);
        if (count($parts) < 9) continue;

        $name = $parts[8];
        $type = $parts[0][0];
        $fullPath = $path . '/' . $name;

        if ($type === 'd') {
            if ($name === '.' || $name === '..') continue;
            $structure[] = [
                'type' => 'directory',
                'name' => $name,
                'path' => $fullPath,
                'children' => getRecursiveFtpList($ftpConn, $fullPath),
            ];
        } elseif ($type === '-') {
            $structure[] = [
                'type' => 'file',
                'name' => $name,
                'path' => $fullPath,
                'size' => (int)$parts[4],
            ];
        }
    }

    return $structure;
}

// Example usage:
$ftpHost = 'ftp.gitbox.net';
$ftpUser = 'your_username';
$ftpPass = 'your_password';

$conn = ftp_connect($ftpHost);
if (!$conn) {
    die("Unable to connect to FTP server");
}

if (!ftp_login($conn, $ftpUser, $ftpPass)) {
    ftp_close($conn);
    die("FTP Login failed");
}

// Optional:Set passive mode
ftp_pasv($conn, true);

$directoryTree = getRecursiveFtpList($conn, '/');

ftp_close($conn);

// Print structure(For debugging)
echo "<pre>";
print_r($directoryTree);
echo "</pre>";

Output structure example

After running the above code, you will get an output similar to:

 Array
(
    [0] => Array
        (
            [type] => directory
            [name] => public_html
            [path] => /public_html
            [children] => Array
                (
                    [0] => Array
                        (
                            [type] => file
                            [name] => index.php
                            [path] => /public_html/index.php
                            [size] => 1234
                        )
                    ...
                )
        )
    [1] => Array
        (
            [type] => file
            [name] => readme.txt
            [path] => /readme.txt
            [size] => 456
        )
)

Things to note

  1. Coding issues : The directory or file name returned by some FTP servers may contain non-UTF-8 characters and need to be transcoded;

  2. Performance issues : Recursive operations may be slow under large directory structures, and caching or paging strategies are appropriately used;

  3. Permission Restrictions : Ensure that FTP users have read permissions to recursive directories, otherwise everything may not be listed;

  4. Passive mode : Some FTP services need to enable passive mode, and use ftp_pasv($conn, true); setting.

Summarize

Through ftp_rawlist and recursive processing, we can fully obtain the directory structure on the FTP server in PHP. This method is highly flexible and can customize data structures on demand, which is very useful for application scenarios such as automated deployment, backup synchronization, file browsing, etc.

Hopefully the complete examples of this article will help you master this technique and apply it to actual development.