Saturday, December 8, 2012

How to transfer files via SFTP in PHP

It's been a long time since my last post and good I'm back again. Anyway, below is my simple script to transfer files via SFTP in PHP. Hope this helps.

<?php

// set your sftp credential (host, port, username, password)
// local file (source file)
// remote file (destination file)


$host = '<host server to connect>';
$port = '<port to connect>';
$user = '<username to sftp>';
$pass = '<password to sftp>';
$lfile = '/path/to/local/file';
$rfile = '/path/to/remote/file';

// use ssh2 php module to connect

// if ssh2 is not installed/enable, please install/enable)
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);

// use sftp to connect
$sftp = ssh2_sftp($connection);

// open stream connection to remote server
$stream = @fopen('ssh2.sftp://'.$sftp.$rfile, 'w');

try {
    if (!$stream) throw new Exception("Could not open remote file: $rfile");

    // get data of the local file
    $data = @file_get_contents($lfile);
    if ($data === false) throw new Exception("Could not open local file: $lfile.");

    // write the data to stream remote file
    if (@fwrite($stream, $data) === false) throw new Exception("Could not send data from file: $lfile.");
    echo 'done!';

} catch (Exception $e) {
    // echo error message
    echo $e->getMessage();
}

// closing the stream
fclose($stream);

?>


Hope this helps and please leave a post if you like it. Thanks!!