phpftp_nlist总是返回false,尽管目录中的文件可以下载

问题描述 投票:0回答:1
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";
?>
    

非常小的可再现示例在下面
$remote_dir = "test/"; ftp_chdir($conn_id, $remote_dir); var_dump(ftp_nlist($conn_id, $remote_dir));
php ftp
1个回答
1
投票
第二行将FTP连接的远程目录更改为

test/

。请注意,没有领先
/
,因此与当前CWD相关。然后,您正在使用相同的变量要求目录列表,这意味着它与最后更改CWD的呼叫相对,实际上有效地更改了CWD。 我可以想到的几个可能的修复。

最简单的可能是@olivier在评论中指出的,只是将

test/test/
用作第二个参数,这意味着“给我当前目录中的文件列表”:
.
第二个选项是首先不要发出

ftp_nlist

命令。这主要取决于您在做什么,以及您是否根本关心CWD,我认为您的代码会做什么。因此,这可能不适合您。

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

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

使用
ftp_chdir
。这将使您可以使用相同的变量使用并讨论相同的目录。再次这样做的选择取决于您的代码的意图。
    

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