PHP ftp_nlist 总是返回 false

问题描述 投票:0回答:1

我试图从 FTP 目录获取文件列表,但 ftp_nlist 函数反复返回 false。我已经在 3 个不同的 FTP 服务器上尝试过,结果相同。在每种情况下,我都能够使用 ftp_fget 连接和下载文件,但 ftp_nlist 永远不起作用。有什么想法吗?这是代码:

<?php

$ftp_server = "myhost";
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";

$remote_dir = "test/"; // The directory on the FTP server
$local_dir = "test/"; // Local directory to save the files

// Connect to the FTP server
$conn_id = ftp_connect($ftp_server);

if (!$conn_id) {
    die("Could not connect to FTP server $ftp_server");
}

// Log in to the server
if (!ftp_login($conn_id, $ftp_user_name, $ftp_user_pass)) {
    die("Could not log in to FTP server with provided credentials.");
}

// Enable passive mode
ftp_pasv($conn_id, true);

if (!ftp_chdir($conn_id, $remote_dir)) {
    ftp_close($conn_id);
    die("Could not change to directory: $remote_dir");
}

// Check if the local directory exists, if not create it
if (!is_dir($local_dir)) {
    if (!mkdir($local_dir, 0777, true)) {
        die("Failed to create local directory: $local_dir");
    }
}

// Download a file - THIS WORKS!
$remote_file='test.txt';
$local_file='test.txt';
$handle = fopen($local_file, 'w');
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
 echo "successfully written to $local_file\n";
} else {
 echo "There was a problem while downloading $remote_file to $local_file\n";
}

// Get the list of files in the remote directory
$files = ftp_nlist($conn_id, $remote_dir);
//$files = ftp_nlist($conn_id, '');

if ($files === false) {
    die("Could not list files in the remote directory: $remote_dir");
}

foreach ($files as $file) {
    // Get the base name of the file
    $basename = basename($file);

    // Build the local file path
    $local_file = $local_dir . $basename;

    // Attempt to download the file
    if (ftp_get($conn_id, $local_file, $file, FTP_BINARY)) {
        echo "Successfully downloaded $file to $local_file\n";
    } else {
        echo "Failed to download $file\n";
    }
}

// Close the FTP connection
ftp_close($conn_id);

echo "FTP download completed.\n";
?>
php ftp
1个回答
0
投票

下面是您的问题的一个非常小的可重现示例

$remote_dir = "test/";   
ftp_chdir($conn_id, $remote_dir);
var_dump(ftp_nlist($conn_id, $remote_dir));

第二行将 FTP 连接的远程目录更改为

test/
。请注意,没有前导
/
,因此它与当前 CWD 相关。然后,您要求使用相同变量的目录列表,这意味着它与更改 CWD 的最后一个调用相关,实际上
test/test/

我能想到一些可能的修复方法。

最简单的可能是@Olivier 在评论中指出,只需使用

.
作为
ftp_nlist
的第二个参数,这意味着“给我当前目录中的文件列表”:

var_dump(ftp_nlist($conn_id, `.`));

第二个选项是首先不发出

ftp_chdir
命令。这主要取决于您还在做什么,以及您是否关心 CWD,我认为您的代码确实关心 CWD。所以这可能不适合你。

最后一个选项是仅使用绝对目录,因此不要使用

test/
,而使用
/test/
。这将允许您使用
ftp_chdir
ftp_nlist
与相同的变量并谈论相同的目录。再次强调,执行此操作的选择取决于代码的意图。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.