Sample code for 30+ languages & platforms
PHP

Check Whether the Last SFTP Read Failed

See more SFTP Examples

Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.

Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle. LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\BinData;
use Chilkat2\SFtp;

// Demonstrates the SFtp.LastReadFailed method, which returns whether the most recent read for a
// handle failed.  The only argument is the handle.  A normal end-of-file is NOT a failure.

$sftp = new SFtp();

// Connect, authenticate, and initialize the SFTP subsystem.
$port = 22;
try {
    $sftp->Connect('sftp.example.com', $port);

    // Normally you would not hard-code the password in source.  You should instead obtain it
    // from an interactive prompt, environment variable, or a secrets vault.
    $password = 'mySshPassword';

    $sftp->AuthenticatePw('mySshLogin', $password);

    $sftp->InitializeSftp();

    $handle = $sftp->OpenFile('subdir/data.txt', 'readOnly', 'openExisting');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$reading = true;
$chunkSize = 4096;
$bd = new BinData();
while ($reading) {
    $sftp->ReadFileBd($handle, $chunkSize, $bd);

    // Distinguish an actual read failure from a normal EOF.  On EOF the read succeeds, returns
    // zero bytes, and LastReadFailed is false.
    if ($sftp->LastReadFailed($handle)) {
        echo 'Read failed: ', $sftp->LastErrorText, "\n";
        exit;
    }

    $reading = !$sftp->Eof($handle);
}

try {
    $sftp->CloseHandle($handle);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo 'Read ', $bd->NumBytes, " bytes with no read failures.\n";

$sftp->Disconnect();