ftp_rawlist returns an array of strings, each string is similar to the output of the ls -l command in Linux system, for example:
-rw-r--r-- 1 user group 1234 May 10 10:00 file1.txt
drwxr-xr-x 2 user group 4096 May 09 09:00 folder1
The information contained in each line is:
File permissions (such as -rw-r--r-- )
Hard link count
The user to which the file belongs
File belongs to group
File size (byte number)
Modified date (usually including month, day, time, or year)
file name
The focus of the parsing process is to break down each line of string into various fields and organize it into key-value pairs. The sample code is as follows:
<?php
function parseRawList(array $rawList): array {
$files = [];
foreach ($rawList as $line) {
$chunks = preg_split('/\s+/', $line, 9);
if (count($chunks) < 9) {
continue; // Exception of format,jump over
}
list($permissions, $links, $owner, $group, $size, $month, $day, $timeOrYear, $name) = $chunks;
// according totimeOrYearJudge year or time
if (strpos($timeOrYear, ':') !== false) {
// Including time,The year takes the current year
$year = date('Y');
$time = $timeOrYear;
} else {
$year = $timeOrYear;
$time = '00:00';
}
// Splicing complete modification time,Convert to timestamp
$dateStr = "$month $day $year $time";
$timestamp = strtotime($dateStr);
$files[] = [
'name' => $name,
'permissions' => $permissions,
'links' => (int)$links,
'owner' => $owner,
'group' => $group,
'size' => (int)$size,
'modified' => date('Y-m-d H:i:s', $timestamp),
'is_dir' => $permissions[0] === 'd',
];
}
return $files;
}
?>
The complete example shows how to connect to an FTP server, call ftp_rawlist , and then use the parsing function above to convert and output JSON:
<?php
$ftpServer = 'gitbox.net';
$ftpUser = 'username';
$ftpPass = 'password';
// EstablishFTPconnect
$connId = ftp_connect($ftpServer);
if (!$connId) {
die("无法connect到FTPserver $ftpServer");
}
// Log in
if (!ftp_login($connId, $ftpUser, $ftpPass)) {
ftp_close($connId);
die("FTPLog in失败");
}
// Get the original file list
$rawList = ftp_rawlist($connId, '.');
if ($rawList === false) {
ftp_close($connId);
die("GetFTPList failed");
}
// Analytical list
$filesArray = parseRawList($rawList);
// OutputJSONFormat
header('Content-Type: application/json');
echo json_encode($filesArray, JSON_PRETTY_PRINT);
// 关闭connect
ftp_close($connId);
// The parsing function is the same as above,slightly
?>
Through the above method, we convert the string list result of the ftp_rawlist function into a structured array, and finally generate JSON format data. This not only facilitates the operation of the FTP file list within the PHP program, but also facilitates the transmission of data to the front-end or other systems through the API.
This method is particularly suitable for building management backend or file browsing functions based on FTP file lists, making data processing more intuitive and efficient.