phpseclib: SFTP Examples and Notes

Action:

<?php
require __DIR__ . '/vendor/autoload.php';

use phpseclib\Net\SFTP;

$sftp = new 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', SFTP::SOURCE_LOCAL_FILE);



?>

Uploading files

The function definition for put() is as follows:

function put($remote_file, $data, $mode = SFTP::SOURCE_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', SFTP::SOURCE_LOCAL_FILE) creates filename.remote on the remote server such that the contents of it and filename.local match. ie. with SFTP::SOURCE_LOCAL_FILE it uploads a file and without it it uploads a string.

Resuming transfers

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

$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE | SFTP::RESUME_START) will append filename.remote to filename.local.

$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE | 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 SFTP::RESUME when they're non-negative. ie. $start could let you write at the end of a file (like SFTP::RESUME) or in the middle of one. $local_start could let you start your reading from the end of a file (like SFTP::RESUME_START) or in the middle of one.