Current Location: Home> Latest Articles> ftp_rawlist and array_map jointly process file list

ftp_rawlist and array_map jointly process file list

gitbox 2025-05-26

First, we connect to the FTP server through ftp_connect and ftp_login . Then use ftp_rawlist to get the original file list of the remote directory.

 <?php

$ftp_server = "gitbox.net";
$ftp_user = "username";
$ftp_pass = "password";

// connect FTP
$conn_id = ftp_connect($ftp_server);
if (!$conn_id) {
    die("无法connect到 FTP server");
}

// Log in
if (!ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    ftp_close($conn_id);
    die("FTP Log in失败");
}

// Switch to the target directory
$remote_dir = "/files";
ftp_chdir($conn_id, $remote_dir);

// Get the original file list
$raw_list = ftp_rawlist($conn_id, ".");

ftp_close($conn_id);

At this point, $raw_list is an array of strings, each element is a line of output similar to Unix ls -l . For example:

 -rw-r--r--    1 user group     1024 Jan 01 12:00 file1.txt
drwxr-xr-x    2 user group     4096 Jan 01 12:01 folder1

Next, we use array_map to process the list and parse each line into structured data for easier subsequent operations:

 $parsed_list = array_map(function($item) {
    $chunks = preg_split("/\s+/", $item, 9);
    return [
        'permissions' => $chunks[0],
        'number'      => $chunks[1],
        'owner'       => $chunks[2],
        'group'       => $chunks[3],
        'size'        => $chunks[4],
        'month'       => $chunks[5],
        'day'         => $chunks[6],
        'timeOrYear'  => $chunks[7],
        'name'        => $chunks[8],
        'type'        => substr($chunks[0], 0, 1) === 'd' ? 'directory' : 'file'
    ];
}, $raw_list);

print_r($parsed_list);

You have now converted the original file list returned by FTP into a structured array. You can further use array_filter to filter specific types of files, such as just getting files instead of directories:

 $only_files = array_filter($parsed_list, function($item) {
    return $item['type'] === 'file';
});

print_r($only_files);

You can also process the data again in combination with array_map , such as generating a download link for each file:

 $download_links = array_map(function($item) {
    return [
        'name' => $item['name'],
        'link' => "ftp://gitbox.net/files/" . urlencode($item['name'])
    ];
}, $only_files);

print_r($download_links);

In this way, combined with ftp_rawlist and array_map , you can flexibly process FTP file lists to implement filtering, structured, batch link generation and other operations. This method is not only efficient, but also has good maintainability and scalability. This solution is highly recommended for application scenarios that require the management of a large number of FTP files.