php - ssh2 上的 opendir 永远不会停止

标签 php php-7 opendir readdir libssh2

我需要通过ssh从远程服务器的根目录中获取一些文件,本地机器使用php7。我制作了这个脚本:

<?php
$strServer = "my-server.com";
$strServerPort = "22";
$strServerUsername = "my.username";
$strServerPassword = "my-password";
$resConnection = ssh2_connect($strServer, $strServerPort);
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
    $files = array();
    $resSFTP = ssh2_sftp($resConnection);
    $dirHandle = opendir("ssh2.sftp://" . intval($resSFTP) . "/");
    while ($dirHandle && ($file = readdir($dirHandle)) !== false) {
        if ($file == "." || $file == "..") {
            continue;
        }
        $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
        file_put_contents('/path/to/dir/' . $file, $strData);
    }
    ssh2_exec($resConnection, 'exit');
    unset($resConnection);
}

die;

它有效,即文件已获取,但脚本永远不会停止。
如果我知道要获取的文件的名称,则脚本将是:

if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
    $files = array();
    $resSFTP = ssh2_sftp($resConnection);
    $file = 'name_of_the_file.xlsx';
    $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
    file_put_contents('/path/to/dir/' . $file, $strData);
}

然后提取文件,脚本在执行结束时停止。

我无法使用 phpseclib,因为它需要 Composer,而且我无法在语言环境计算机上使用它。

如何在不让脚本无限运行的情况下对 opendir()readdir() 执行操作?

最佳答案

尝试在file_put_contents之后中断

例如:

if (file_put_contents('/path/to/dir/' . $file, $strData) !== false) {
    break;
}

或者作为最佳方法,您可以在放入数据后直接使用linedir

do {
    if ($file == "." || $file == "..") {
        continue;
    }
    $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
    if (file_put_contents('/path/to/dir/' . $file, $strData)) {
        break;
    }
} while ($dirHandle && ($file = readdir($dirHandle)) !== false);

closedir($dirHandle);

关于php - ssh2 上的 opendir 永远不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906032/

相关文章:

javascript - 如何将 GET 值附加到页面上每个链接的末尾

php - 如何使用 PHP Laravel 合并数组?

php - PHP 7+ 中的命名参数解决方案

javascript - 从客户端计算机读取目录内容 - PHP

PHP Carbon 需要几分钟并转换为天

php - 在 PHP7/HHVM 的新 MongoDB 库中使用正则表达式

c - 第二次调用 opendir 时出现段错误

c - "Double dot"C 中的目录名?

syntax-error - php 7 支持按引用传递吗?

在 PHP 7 中不鼓励使用 Eval