phpseclib: SFTP Examples and Notes

Action:

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

$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');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);



?>

Uploading files

The function definition for put() is as follows:

function put($remote_file, $data, $mode = NET_SFTP_STRING, $start = -1, $local_start = -1)

Uploading strings vs. files

$sftp->put('filename.remote', 'filename.local') creates filename.remote on the remote server with 'filename.local' as the contents.

$sftp->put('filename.remote', 'xxx', NET_SFTP_LOCAL_FILE) creates filename.remote on the remote server such that the contents of it and filename.local match. ie. with NET_SFTP_LOCAL_FILE it uploads a file and without it it uploads a string.

Resuming transfers

$sftp->put('filename.remote', 'xxx', NET_SFTP_RESUME) will append 'xxx' to filename.remote.

$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME_START) will append filename.remote to filename.local.

$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME) will append all but the first $sftp->size('filename.remote') bytes of filename.local to filename.remote. The idea being that if your transfer is interupted you can restart it.

Positional control

$start and $local_start give you more fine grained control over this process and take precident over NET_SFTP_RESUME when they're non-negative. ie. $start could let you write at the end of a file (like NET_SFTP_RESUME) or in the middle of one. $local_start could let you start your reading from the end of a file (like NET_SFTP_RESUME_START) or in the middle of one.