<?php
// FTP Server information
$ftp_server = "gitbox.net";
$ftp_user = "your_username";
$ftp_pass = "your_password";
// Establish a connection and log in
$conn_id = ftp_connect($ftp_server);
if (!$conn_id) {
die("Unable to connect to FTP server {$ftp_server}");
}
if (!ftp_login($conn_id, $ftp_user, $ftp_pass)) {
ftp_close($conn_id);
die("FTP Login failed");
}
// Switch to the target directory
$remote_dir = "/path/to/your/dir";
if (!ftp_chdir($conn_id, $remote_dir)) {
ftp_close($conn_id);
die("Failed to switch directory: {$remote_dir}");
}
// Get the directory list,similar ls -l Output
$raw_list = ftp_rawlist($conn_id, ".");
// Parses each line,示例Output解析结果
foreach ($raw_list as $line) {
/**
* Typical format examples:
* -rw-r--r-- 1 owner group 1234 May 25 12:34 filename.txt
* drwxr-xr-x 2 owner group 4096 Apr 10 2023 dirname
*
* Regular description:
* ^([\-ld]) File Type:-Normal files,lSymbol Links,dTable of contents
* ([rwx\-]{9}) Permissions9character
* \s+\d+\s+ Spaces+number(Number of links) + Spaces
* (\S+)\s+ owner
* (\S+)\s+ Group
* (\d+)\s+ File size
* (\w{3})\s+ Month abbreviation
* (\d{1,2})\s+ date
* ([\d:]{4,5}|\d{4})\s+ Time or year
* (.+)$ file name
*/
$pattern = '/^([\-ld])([rwx\-]{9})\s+\d+\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w{3})\s+(\d{1,2})\s+([\d:]{4,5}|\d{4})\s+(.+)$/';
if (preg_match($pattern, $line, $matches)) {
list(, $type, $perms, $owner, $group, $size, $month, $day, $time_or_year, $filename) = $matches;
echo "type: " . ($type === 'd' ? 'Table of contents' : ($type === '-' ? 'document' : 'Link')) . "\n";
echo "Permissions: $perms\n";
echo "owner: $owner\n";
echo "Group: $group\n";
echo "size: $size byte\n";
echo "Modification time: $month $day $time_or_year\n";
echo "file name: $filename\n";
echo "---------------------\n";
} else {
echo "Unable to parse the line: $line\n";
}
}
// Close the connection
ftp_close($conn_id);
?>