Development

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and permissions.

This uses the ftp_rawlist() method and splits the string into an array for each item in the directory, this includes files and folders.

This method also does just one FTP call per directory, instead of having to call ftp_size() on each file in the directory.

if (is_array($children = @ftp_rawlist($conn, "."))) {

    $items = [];

    foreach ($children as $child) {

        $split = preg_split("/\s+/", $child);

        [$item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time'], $item['name']] = $split;

        $item['type'] = $split[0][0] === 'd' ? 'directory' : 'file';

        $items[] = $item;

    }

}

A sample output of $items

[
  {
    "rights": "-rw-r--r--",
    "number": "1",
    "user": "ftp",
    "group": "ftp",
    "size": "83886104",
    "month": "July",
    "day": "26",
    "time": "2023",
    "name": "sample.txt",
    "type": "file"
  },
  {
    "rights": "-rw-r--r--",
    "number": "1",
    "user": "ftp",
    "group": "ftp",
    "size": "1821",
    "month": "July",
    "day": "26",
    "time": "2023",
    "name": "other.txt",
    "type": "file"
  }
]

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

2 years ago