0

我们试图仅从远程服务器移动文件并将文件目录放入我们的数据库中,因此我们需要能够区分文件和目录。我们已经成功地能够通过 SSH2 进行连接,并且能够读取和显示远程路径顶级目录中的文件和目录。但是,我们无法找到一个 php 脚本,它可以让我们找到返回的名称是目录还是文件。下面是我们尝试过的几个例子。非常感谢任何帮助,我们提前感谢您。

$connection = ssh2_connect('www.myremote.com', 22);
ssh2_auth_password($connection, 'user', 'pw');

$sftp = ssh2_sftp($connection);

// THIS WORKS NICELY TO DISPLAY NAME FROM REMOTE SERVER
$handle = opendir("ssh2.sftp://$sftp/remotepath/");
echo "Directory handle: $handle<br>";
echo "Entries:<br>";
while (false != ($entry = readdir($handle))){
    echo "$entry<br>";
}

// ONE OPTION THAT DOES NOT WORK
$handle = opendir("ssh2.sftp://$sftp/remotepath/");
echo "<br><br>2Directory handle: $handle<br>";
echo "4Entries:<br>";
while (false != ($entry = readdir($handle))){
    if (is_dir(readdir($handel.''.$entry) ) ) {echo "<strong>$entry</strong><br>"; } else {
    echo "$entry<br>"; //}
}

// ANOTHER OPTION THAT RETURNS AN EMPTY RESULT
$files = scandir('ssh2.sftp://'.$sftp.'/remotepath/');
foreach ($files as $file):
    if (is_dir('ssh2.sftp://'.$sftp.'/remotepath/'.$file) ) {"<strong>".$file."</strong><br>"; } else { $file.'<br>'; } 
endforeach;
4

1 回答 1

0

如果您使用 Linux 命令行 find 这将有所帮助:

这是您仅找到名为blah的文件的方式:

find . -type f -name *blah*

这是您仅找到名为blah的目录的方式:

find . -type d -name *blah*

在这种情况下,您可以通过以下方式找到 /tmp 目录中的所有文件(无需进入 /tmp (maxdepth 1) 的子目录),命名为:

$connection->exec('find /tmp -maxdepth 1 -type f -name "*"');

编辑:

好的,所以这里有更多的代码。这将连接到服务器并回显主目录中所有目录的列表,然后是主目录中的所有文件:

$connection = ssh2_connect($host, 22);
ssh2_auth_password($connection, $user, $pass);

$the_stream = ssh2_exec($connection, '/usr/bin/find ~ -maxdepth 1 -type d');
stream_set_blocking($the_stream, true);
$the_result = stream_get_contents($the_stream);
echo "Directories only: <br><pre>" . $the_result . "</pre>";
fclose($the_stream);

$the_stream = ssh2_exec($connection, '/usr/bin/find ~ -maxdepth 1 -type f');
stream_set_blocking($the_stream, true);
$the_result = stream_get_contents($the_stream);
echo "Files only: <br><pre>" . $the_result . "</pre>";
fclose($the_stream);

您应该能够将 $the_result 解析为一个数组,方法是在换行符或类似的部分进行拆分,并仅获取文件或目录。从查找中删除“-maxdepth 1”,您将递归所有子目录。

于 2013-08-02T23:14:21.543 回答