2

I am currently struggling with using the SSH2 built-in libraries for PHP (running version 5.5). I am trying to upload a file to an SFTP server as the title states however I keep getting a "stream operation failed" error message.

After attempting to debug the code itself the connection works, the sftp resource is assigned an ID correctly, however when fopen is called for writing the file directly to the remote server it fails.

// 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);

And finally the fopen() call:

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

I added debug messages in my own code to verify if the data from the _settings array is also used correctly and it is, however I can't explain the stream error.

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

As a note the file does not exist on the remote host but according to my knowledge 'w' mode in PHP fopen() should create the file if it does not exist.

I can't use the other PHP library as our whole project uses the builtin ssh2 libraries and the person in charged told me to not use it as it works fine everywhere else.

4

2 回答 2

2

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

谢谢大家的提示和帮助。

于 2015-03-10T08:44:28.767 回答
2

我认为如果你使用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 的优点之一是它可以进行日志记录,因此如果这不起作用,您可以define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);在包含 Net/SFTP.php 之后执行此操作,然后echo $sftp->getLog()在它失败后执行此操作。如果它仍然不起作用,这可能会提供一些关于正在发生的事情的见解。

于 2015-03-09T18:00:26.410 回答