PHP SSH2 操作在尝试将文件上载到服务器时失败


PHP SSH2 operations failing when attempting to upload file to server

我目前正在为PHP使用SSH2内置库(运行版本5.5)而苦苦挣扎。我正在尝试将文件上传到SFTP服务器,如标题所述,但是我不断收到"流操作失败"错误消息。

在尝试调试代码本身后,连接工作,sftp 资源被正确分配一个 ID,但是当调用 fopen 将文件直接写入远程服务器时,它会失败。

// open Live environment if we are not in dev
$connection = ssh2_connect($this->_settings['source_host'], 22);
$authSuccess = ssh2_auth_password($connection, $this-  >_settings['source_user'], $this->_settings['source_password']);
$sftp = ssh2_sftp($connection);

最后是 fopen() 调用:

if($operation == 'export') {
    $handle = fopen("ssh2.sftp://".$sftp."/remotecopy/IN/".$filename, $mode);
}

我在自己的代码中添加了调试消息,以验证 _settings 数组中的数据是否也正确使用,但是我无法解释流错误。

Message:  fopen(): Unable to open ssh2.sftp://Resource id #173/PATH GOES HERE/filename.xxx on remote host
Message:  fopen(ssh2.sftp://Resource id #173/PATH GOES HERE/filename.xxx): failed to open stream: operation failed

请注意,该文件在远程主机上不存在,但根据我的知识,如果文件不存在,PHP fopen() 中的"w"模式应该创建该文件。

我不能使用其他PHP库,因为我们的整个项目都使用内置的ssh2库,负责人告诉我不要使用它,因为它在其他任何地方都可以正常工作。

我认为如果你使用phpseclib,一个纯粹的PHP SFTP实现,你会更容易。

<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);
?>

phpseclib 的一个好处是它的日志记录,所以如果这不起作用,你可以在包含 Net/SFTP 后执行define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);.php然后在失败后执行echo $sftp->getLog()。如果它仍然不起作用,这可能会提供一些关于正在发生的事情的见解。

答案很简单,我在远程服务器上的路径格式不正确。验证我的设置后,它工作正常。

谢谢大家的提示和帮助。