Question

While trying to list the files present in a remote sftp location using php, I get this error:

Error 324 (net::ERR_EMPTY_RESPONSE):

The server closed the connection without sending any data. On my another lamp server the same code works fine. Please point where I am missing something if you can help please. Thanks in advance.

function listBuildFiles() {

global $sftp_host, $sftp_username, $sftp_password, $sftp_path;
$connection = ssh2_connect($sftp_host);
// Authenticate
if (!ssh2_auth_password($connection, $sftp_username, $sftp_password)) {
    throw new Exception('Unable to connect.');
}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) {
    throw new Exception('Unable to create SFTP connection.');
}

/**
 * Now that we have our SFTP resource, we can open a directory resource
 * to get us a list of files. Here we will use the $sftp resource in
 * our address string as I previously mentioned since our ssh2://
 * protocol allows it.
 */
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp$sftp_path");
    $i=0;
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle))) {
    if ($file != '.' && $file != '..') {
        $files[$i] = $file;
        $i++;
    }
}

echo '<select name="buildName">';
echo '<option>Please Select a build</option>';
foreach ($files as $filename) {
      echo "<option value=\"$filename\">$filename</option>";
    }
echo '</select>';
ssh2_exec($connection, "exit");

Thanks, Ujjwal

Was it helpful?

Solution

With phpseclib, a pure PHP SFTP implementation, you can see the full logs of what's going on. Example:

<?php
include('Net/SFTP.php');

define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);

$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');

echo $ssh->getLog();
print_r($ssh->getErrors());
?>

The developer of phpseclib is pretty proactive about providing support too so if you can't figure it out from the logs or error messages (s)he probably can.

OTHER TIPS

Just to make sure there is no problem on the server side you can open a console and try a raw ssh connection in verbose mode:

ssh -v youruser@yourhost.com

this traces all the interactions between server and client, maybe gives you some clue from the server side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top