我编写了一个 php 脚本,在带有 php7.3 的 apache 服务器上本地执行,执行以下操作:
- 通过 SSH2 访问服务器
- 检查文件是否存在
- 紧密连接
- 打印 JSON 数据对象作为响应。
脚本除了关闭连接外没有问题。 如果我添加ssh2_disconnect函数,则没有响应返回。我错过了什么? 这是我的代码:
<?php
error_reporting(1);
ini_set('display_errors', '1');
$config = ["server"=>"10.1.201.1","port"=>"22","user"=>"root","password"=>"root","folder"=>"/"];
$files = ["file1.pdf","file2.pdf"];
$result = [];
$ftpConnect = ssh2_connect($config['server'],$config['port']);
ssh2_auth_password($ftpConnect,$config['user'],$config['password']);
$sftp = ssh2_sftp($ftpConnect);
foreach ($files as $file){
$fileExists = file_exists("ssh2.sftp://". intval($sftp) . $config['folder'] . $file);
if($fileExists){
$result[$file]= ["status"=>"Found"];
}else $result[$file]= ["status"=>"Not found"];
}
//ssh2_disconnect($ftpConnect); only if uncommented, script wouldn't work
header('content-type:text/json; charset=UTF-8');
echo json_encode($result);
?>
它似乎与版本相关。ssh2_disconnect
是您唯一可用于PECL ssh2 >= 1.0
所有其他ssh2
功能都可用于PECL ssh2 >= 0.9.0.
下面的注释让我们认为 php>= 7 也是需要的。
http://php.net/manual/function.ssh2-disconnect.php#123413
以下是他建议在没有可用ssh2_disconnect
的情况下关闭连接的方式:
$session = null; unset($session); // close connection
似乎在最近的实现中,我们可以通过 ssh2-断开连接成功关闭与 SFTP 的连接
因此,对于任何阅读本文的人来说,我认为这是现在最好的解决方案。
SFTP 服务器日志中的示例:
xxx 的客户端发送SSH_DISCONNECT消息:PECL/ssh2 (http://pecl.php.net/packages/ssh2) (应用程序已断开连接)
(传输文件时也没有错误)