Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // 处理跨域
// FTP配置
$ftpHost = '101.43.223.180';
$ftpPort = 21;
$ftpUser = 'duoletest';
$ftpPass = 'iC5sQ2eZ3tI7kM9cD6';
$rootPath = '/home/duoletest/tmp'; // 默认根路径
// 获取请求路径
$currentPath = isset($_GET['path']) ? $_GET['path'] : $rootPath;
try {
// 连接FTP
$conn = ftp_connect($ftpHost, $ftpPort) or throw new Exception("无法连接FTP服务器");
// 登录
ftp_login($conn, $ftpUser, $ftpPass) or throw new Exception("登录失败");
// 启用被动模式
ftp_pasv($conn, true);
// 获取文件列表(原始格式)
$list = ftp_rawlist($conn, $currentPath);
if ($list === false) throw new Exception("获取文件列表失败");
// 解析文件列表
$files = [];
foreach ($list as $item) {
if (preg_match('/^([\-dl])[rwx\-]{9}.*\s(\d+)\s(\w+\s+\d+\s+[\d:]+)\s(.+)$/', $item, $matches)) {
$type = $matches[1] === 'd' ? 'directory' : 'file';
$size = (int)$matches[2];
$date = date('Y-m-d H:i', strtotime($matches[3]));
$name = $matches[4];
$files[] = [
'name' => $name,
'type' => $type,
'size' => $size,
'date' => $date,
'path' => rtrim($currentPath, '/') . '/' . $name
];
}
}
// 返回结果
echo json_encode([
'success' => true,
'path' => $currentPath,
'files' => $files
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
} finally {
isset($conn) && ftp_close($conn);
}