Segmentation fault on fopen using sftp and ssh2

Found the answer here on StackOverflow: https://stackoverflow.com/a/40972584/2520795

It seems since this PHP update, you have to surround your host part (result of ssh2_sftp()) with intval():

$handle = opendir("ssh2.sftp://".intval($sftp)."/path/to/directory");

In my case there was a fopen instead of an opendir, but the solution is the same.


You may experience "segmentation fault" issue even with intval($sftp) solution if you're closing connection with ssh2_disconnect(). The right solution is to close SFTP connection before closing SSH2-connection by unset($sftp) or $sftp = null. Here's my fully working example of reading remote file:

if (!$ssh2_connection = ssh2_connect($host, $port)) {
    die("Failed to connect\n");
}
if (!ssh2_auth_password($ssh2_connection, $username, $password)) {
    die("Failed to login\n");
}
if (!$sftp_connection = ssh2_sftp($ssh2_connection)) {
    die("Failed to open SFTP session\n");
}
if (!$fh = fopen("ssh2.sftp://".intval($sftp_connection).$path, 'r')) {
    die("Failed to open file\n");
}
while (($s = fgets($fh)) !== false) {
    echo $s;
}
fclose($fh);
unset($sftp_connection);
if (!ssh2_disconnect($ssh2_connection)) {
    die("Failed to disconnect\n");
}

P.S. Also instead of "segmentation fault" you may see something like:

php: channel.c:2570: _libssh2_channel_free: Assertion `session' failed.

Aborted

My solution solves it.


In our case, the intval() didn't solve the segmentation fault. However, changing the call format did work:

fopen("ssh2.sftp://{$username}:{$password}@{$host}:{$port}/{$absolutePath}/{$filename}", 'w');