PHP code example of idct / sftp-client

1. Go to this page and download the library: Download idct/sftp-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

idct / sftp-client example snippets


use IDCT\Networking\Ssh\Auth\Credentials;
use IDCT\Networking\Ssh\SftpClient;

$client = new SftpClient();
$client->setCredentials(Credentials::withPassword('alice', 'super-secret'));
$client->connect(
    host: 'sftp.example.com',
    port: 22,
    timeoutSeconds: 5,
    expectedFingerprint: 'a1b2c3...your sha1 hex...',
);

$client->upload('/local/path/file.bin', '/remote/incoming/file.bin');
$client->download('/remote/outgoing/report.csv', '/local/reports/report.csv');

$client->close();

use IDCT\Networking\Ssh\Auth\Credentials;
use IDCT\Networking\Ssh\Auth\StaticCredentialsLoader;

// password
Credentials::withPassword('alice', 'secret');

// public key
Credentials::withPublicKey('alice', '/path/id_rsa.pub', '/path/id_rsa', 'passphrase-or-null');

// multi-factor: both pubkey AND password legs must succeed
Credentials::withBoth('alice', 'secret', '/path/id_rsa.pub', '/path/id_rsa');

// anonymous (ssh2_auth_none)
Credentials::withNone('guest');

$client->setCredentialsLoader($myVaultLoader);     // fires on every connect()
// Mutually exclusive with setCredentials().

use IDCT\Networking\Ssh\Auth\AuthFailureRateLimiter;

$client->setAuthFailureRateLimiter(new AuthFailureRateLimiter(
    thresholdFailures: 3,
    baseDelayMs: 1_000,
    maxDelayMs: 60_000,
));

use IDCT\Networking\Ssh\HostKey\FingerprintAlgorithm;
use IDCT\Networking\Ssh\HostKey\FingerprintEncoding;

$client->connect(
    'sftp.example.com',
    22,
    timeoutSeconds: 5,
    expectedFingerprint: '5b:32:...:...',
    fingerprintAlgorithm: FingerprintAlgorithm::Sha256,   // default
    fingerprintEncoding:  FingerprintEncoding::Hex,       // default
);

use IDCT\Networking\Ssh\KnownHosts\UnknownHostPolicy;

$client->connect(
    'sftp.example.com',
    22,
    knownHostsFile: '/etc/idct/known_hosts',
    onUnknownHost: UnknownHostPolicy::Reject,           // or TrustOnFirstUse
);

$client->upload($local, $remote);                // SFTP, atomic by default
$client->download($remote, $local);              // SFTP
$client->scpUpload($local, $remote);             // SCP (never atomic — one-shot push)
$client->scpDownload($remote, $local);           // SCP

$client->remove('/data/file.bin');
$client->rename('/data/old.bin', '/data/new.bin');

$client->makeDirectory('/data/sub', mode: 0755, recursive: true);
$client->removeDirectory('/data/sub');           // must be empty

$client->stat('/data/file.bin');                 // stat-style array
$client->fileExists('/data/file.bin');           // bool
$client->getFileList('/data');                   // list<string>, no . / ..
$client->getFileList('/data', 

$client->disableAtomicUploads();

// Auto-detect offset from any existing partial.
$client->resumeUpload('/local/giant.iso', '/remote/giant.iso');

// Or pass an explicit byte offset.
$client->resumeUpload('/local/giant.iso', '/remote/giant.iso', offset: 1_500_000);

// Downloads mirror it.
$client->resumeDownload('/remote/giant.iso', '/local/giant.iso');

// Upload from any PHP stream resource.
$stream = fopen('http://my-minio:9000/bucket/key', 'rb');
$client->uploadStream($stream, '/remote/from-s3.bin');
fclose($stream);

// Download into any stream resource (returns bytes written).
$sink  = fopen('php://temp/maxmemory:0', 'r+b');
$bytes = $client->downloadStream('/remote/source.bin', $sink);
rewind($sink);
// … now hand $sink to whatever consumer wants the bytes.

use IDCT\Networking\Ssh\Progress\ProgressListenerInterface;

final class CliProgressBar implements ProgressListenerInterface
{
    public function started(string $operation, ?int $totalBytes): void
    {
        echo "[$operation] starting ($totalBytes bytes)\n";
    }
    public function progress(int $bytesDone): void
    {
        echo "\r  $bytesDone bytes …";
    }
    public function completed(int $bytesDone): void
    {
        echo "\r  done. $bytesDone bytes.\n";
    }
    public function failed(\Throwable $e): void
    {
        echo "\n  FAILED: " . $e->getMessage() . "\n";
    }
}

$client->upload('/local/big.iso', '/remote/big.iso', progress: new CliProgressBar());

$client->setChunkSize(64 * 1024);   // 64 KiB chunks → ~16 progress events per MiB

use IDCT\Networking\Ssh\Directory\ConflictPolicy;
use IDCT\Networking\Ssh\Directory\SymlinkPolicy;

// Upload a local tree, mirroring its layout under /backup/.
$result = $client->uploadDirectory(
    '/local/src',
    '/backup/src',
    onConflict: ConflictPolicy::Skip,        // or Overwrite (default) / Fail
    symlinks:   SymlinkPolicy::Skip,         // or Follow (with cycle detection)
    bestEffort: true,                        // collect failures instead of aborting
);
echo "Uploaded {$result->filesTransferred} files, "
   . "{$result->bytesTransferred} bytes, "
   . count($result->skipped) . " skipped, "
   . count($result->failures) . " failures.\n";

// Mirror it back.
$client->downloadDirectory('/backup/src', '/local/restore');

// Walk arbitrary trees (post-order generator: children before parents).
foreach ($client->walk('/backup') as $entry) {
    echo $entry->path . " ({$entry->type->name})\n";
}

// rm -rf on the remote.
$client->removeDirectoryTree('/backup/obsolete');

use IDCT\Networking\Ssh\Retry\ExponentialBackoffRetryPolicy;
use IDCT\Networking\Ssh\Retry\NoRetryPolicy;

$client = new SftpClient(
    enableFileSizeVerification: false,
    ssh2: null,
    retryPolicy: new ExponentialBackoffRetryPolicy(maxRetries: 10, baseMs: 100),
);

// Or swap at runtime.
$client->setRetryPolicy(new NoRetryPolicy());

use IDCT\Networking\Ssh\Exception\SshException;
use IDCT\Networking\Ssh\Retry\RetryPolicyInterface;

final class MyPolicy implements RetryPolicyInterface
{
    public function nextDelayMs(int $attempt, SshException $lastError): int
    {
        return $attempt > 3 ? 0 : 500;        // 500 ms each, 3 attempts max
    }
}

use IDCT\Networking\Ssh\Checksum\ShellSumRemoteHasher;
use IDCT\Networking\Ssh\Checksum\RedownloadRemoteHasher;

// Option 1: run `sha256sum` on the server (needs shell access).
$client->setRemoteHasher(new ShellSumRemoteHasher('sha256', 'sha256sum'));

// Option 2: re-download the file and hash it locally
// (no server dependency, but doubles transfer time).
$client->setRemoteHasher(new RedownloadRemoteHasher('sha256'));

// All subsequent upload / resumeUpload / download / resumeDownload
// transfers now compare local + remote digests after the transfer and
// throw TransferException on mismatch.
$client->upload('/local/critical.bin', '/remote/critical.bin');

$client->setLocalPrefix('/var/local/inbox/');
$client->setRemotePrefix('/uploads/');

$client->upload('/var/sources/report.csv');                   // → /uploads/report.csv (basename)
$client->upload('/var/sources/report.csv', 'q3/report.csv');  // → /uploads/q3/report.csv
$client->upload('/var/sources/report.csv', '/abs/dest.csv');  // → /abs/dest.csv (absolute bypasses prefix)

use IDCT\Networking\Ssh\Exception;

try {
    $client->download('/data/big.bin', '/local/big.bin');
} catch (Exception\ConnectionException) {
    // reconnect
} catch (Exception\TransferException $e) {
    // log, alert, retry
} catch (Exception\SshException $e) {
    // anything else from this library — single SshException root grabs all of them
}

$client->setLogger(new Monolog\Logger('sftp'));
$client->setLogContext(['request_id' => 'abc-123', 'tenant' => 'acme']);
bash
sudo apt-get install php-ssh2
bash
apk add php-pecl-ssh2