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コマンドラインを使用する場合、これが役立ちます:

これは、 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 に答える