Downloading and Uploading Files Over SFTP with PHP and SSH2

This is a code I used today to connect my customer SFTP server to download his Dialer leads file . SSH2 PHP extension needed to be installed and enabled in php.ini file .

1 - Install the prerequisites 
        yum install gcc php-devel php-pear libssh2 libssh2-devel make
2 - Install the SSH2 extension 
        pecl install -f ssh2
3 - Enable it in php.ini
        echo >> /etc/php.ini
4 - Restart apache
        service httpd restart

- Connecting and Uploading File to SFTP using SSH2 extension 

$server = '';
$port = '22222';
$username = 'MYSFTPUSER';
$password = 'MYSFTPPASSWORD';

// connect
$connection = ssh2_connect($server, $port);
        if (ssh2_auth_password($connection, $username, $password)) {
                // initialize sftp
                $sftp = ssh2_sftp($connection);
                // Upload file
                echo "Connection successful, uploading file now..."."\n";

                $file = 'omid.txt';
                $contents = file_get_contents($file);
                file_put_contents("ssh2.sftp://{$sftp}/MyRemoteHomeFolder/{$file}", $contents);

        } else {
                echo "Unable to authenticate with server"."\n";

- Downloading all  files from SFTP using SSH2 extension 

 $sftpconnection = ssh2_connect($sftpserver, $sftpport);
          if (!ssh2_auth_password($sftpconnection, $sftpusername, $sftppassword)) throw new Exception('Unable to connect.');
           // Create our SFTP resource
          if (!$sftp = ssh2_sftp($sftpconnection)) throw new Exception('Unable to create SFTP connection.');
          $localDir  = '/usr/local/src/downloads/';
          $remoteDir = '/myremotefolder/';
          $files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
          if (!$dir = opendir("ssh2.sftp://$sftpconnection$remoteDir"))
                die('Failed to open the directory.');

          if (!$remote = fopen("ssh2.sftp://$sftpconnection$remoteDir$file", 'r'))
                  die("Failed to open remote file: $file\n");

          if (!$local = fopen($localDir . $file, 'w'))
             die("Failed to create local file: $file\n");

         $read = 0;
         $filesize = filesize("ssh2.sftp://$sftpconnection/$remoteDir$file");
          while ( ($read < $filesize) && ($buffer = fread($remote, $filesize - $read)) )
           $read += strlen($buffer);
           if (fwrite($local, $buffer) === FALSE)
             echo "Failed to write to local file: $file\n";



  1. Instead of using SSH2 PHP extension, I think it is better to use PHP sftp library called phpseclib. This library makes using sftp in PHP really easy and quick.


Post a Comment