0

I'm trying to write stuff via SFTP and something strange is happening.

Here's a generic sample script:

<?php

$resConnection = ssh2_connect("<url>");

if (ssh2_auth_password($resConnection, "<name>", '<password>')){
    //Initialize SFTP subsystem
    echo "connected";

    $resSFTP = ssh2_sftp($resConnection);
    $resFile = fopen("ssh2.sftp://{$resSFTP}/"."test", 'w');
    fwrite($resFile, "Testing");
    fclose($resFile);
} else {
    echo "Unable to authenticate on server";
}

And the output for it is something like this:

root@0fb6a2a1af08:/var/www# php test.php
connected
Warning: fopen(ssh2.sftp://Resource id #5/test): failed to open stream: operation failed in /var/www/test.php on line 8

Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 9

Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/test.php on line 10

So basically it connects but cannot write anything. The same code with the same credentials works fine on another machine.

Is it possible that some specific configuration on SFTP side prevents me from writing?

Gino Pane
  • 4,740
  • 5
  • 31
  • 46
  • Maybe a filesystem permission problem? – Emanuel Vintilă Feb 19 '20 at 11:18
  • @EmanuelVintilă that's what I'm trying to find out :) The remote user is the same, so permissions should be the same in both cases I believe. – Gino Pane Feb 19 '20 at 11:24
  • Have you checked the error message? The warning that prints out `Resource id #5` sounds pretty obvious to me: why do you want to cast a ressource to a string? – Nico Haase Feb 19 '20 at 12:40
  • @NicoHaase I've responded with my own answer below. Basically, it is how it was supposed to work, but due to several bugs it may not work. So it is better to explicitly cast it it int. – Gino Pane Feb 19 '20 at 14:03

1 Answers1

0

Ok, it is connected with this bugs:

The solutions for now is to use intval around the resource string as it is said in docs: https://www.php.net/manual/ru/function.ssh2-sftp.php

$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r'); 
Gino Pane
  • 4,740
  • 5
  • 31
  • 46