PHP and SSH2 Class – Easily put/get files

By | April 5, 2013

I wrote a short little helper class for retrieving files using the ssh2 library w/PHP.  Don’t forget to enable/install it to your PHP installation!

_server = $server;
			$this->_username = $username;
			$this->_password = $password;
			$this->_resource = false;
			
			try
			{
				$this->OpenConnection();
			}
			catch ( Exception $e )
			{
				throw new Exception('Unable to connect to SFTP server! Error:' . $e->getMessage());
			}
		}
		
		private function OpenConnection()
		{
			try
			{
				$this->_resource = ssh2_connect($this->_server);
			}
			catch ( Exception $e )
			{
				throw new Exception('Unable to ssh2_connect to $this->_server Error: ' . $e->getMessage());
			}
			
			// authenticate
			if ( $this->_resource !== false )
			{
				
				try
				{
					if ( ssh2_auth_password($this->_resource, $this->_username, $this->_password) )
					{
						return true;
					}
				}
				catch ( Exception $e )
				{
					throw new Exception('Unable to ssh2_auth_password to $this->_server Error: ' . $e->getMessage());
				}
			}
			
			throw new Exception('Unable to authentication to server successfully');
		}
		
		private function CreateSession()
		{
			// TODO: Error checking
			return ssh2_sftp($this->_resource);
		}
	
	
		public function PutFile($source_file, $destination_file)
		{
			try
			{
				$sftp = $this->CreateSession();
			
				$sftpStream = fopen('ssh2.sftp://'.$sftp.$destination_file, 'w');
			
			    if (!$sftpStream)
			    {
			        throw new Exception("Could not open remote file: $destination_file");
			    }
			    
			    $data_to_send = file_get_contents($source_file);
			    
			    if ($data_to_send === false)
			    {
			        throw new Exception("Could not open local file: $source_file.");
			    }
			    
			    if (fwrite($sftpStream, $data_to_send) === false)
			    {
			    	
			        throw new Exception("Could not send data from file: $source_file.");
			    }
			    
			    echo "File uploaded successfully: " . basename($source_file) . "\r\n";
			    
			    fclose($sftpStream);            
			}
			catch (Exception $e)
			{
				fclose($sftpStream);
				
			    throw new Exception('Exception: ' . $e->getMessage());
			}
		
			return true;
		}
		
		public function GetFileList()
		{
			$files = array();
			
			try
			{
				$sftp = $this->CreateSession();
				
				$dirHandle = opendir("ssh2.sftp://$sftp/");
			 
				// Properly scan through the directory for files, ignoring directory indexes (. & ..)
				while (false !== ($file = readdir($dirHandle)))
				{
				    if ($file != '.' && $file != '..')
				    {
				        $files[] = $file;
				    }
				}
			}
			catch ( Exception $e )
			{
				throw new Exception('Unable to retrieve file list from server: ' . $e->getMessage());
			}
			
			return $files;
		}
		
		public function GetFile($fileName)
		{
			try
			{
				$sftp = $this->CreateSession();
				
		        // Remote stream
		        if (!$remoteStream = @fopen("ssh2.sftp://$sftp/$fileName", 'r'))
		        {
		            throw new Exception("Unable to open remote file: $fileName");
		        } 
		 
		        // Get our file from the remote stream
		        $contents = '';
		        $read = 0;
		        $fileSize = filesize("ssh2.sftp://$sftp/$fileName");
		        while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read)))
		        {
		            // Increase our bytes read
		            $read += strlen($buffer);
		            
		            $contents .= $buffer;
		        }
		 
		        // Close our stream
		        fclose($remoteStream);
		        
		        return $buffer;
	        }
	        catch ( Exception $e )
	        {
	        	throw new Exception($e->getMessage());
	        }
	        
	        return NULL;
		}
	}
?>

 

Credits to Random Drake for the listing/downloading code

One thought on “PHP and SSH2 Class – Easily put/get files

Leave a Reply to Viji Cancel reply

Your email address will not be published. Required fields are marked *