Sample code for 30+ languages & platforms
PHP

SFTP Read Text File

See more SFTP Examples

Demonstrates how to open a text file on the SSH server and read text.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\SFtp;

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$sftp = new SFtp();

// Set some timeouts, in milliseconds:
$sftp->ConnectTimeoutMs = 5000;
$sftp->IdleTimeoutMs = 15000;

// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
$hostname = 'sftp.example.com';
$port = 22;
try {
    $sftp->Connect($hostname, $port);

    // Authenticate with the SSH server.  Chilkat SFTP supports
    // both password-based authenication as well as public-key
    // authentication.  This example uses password authenication.
    $sftp->AuthenticatePw('myLogin', 'myPassword');

    // After authenticating, the SFTP subsystem must be initialized:
    $sftp->InitializeSftp();

    // Open a file for reading.
    $handle = $sftp->OpenFile('myTest.txt', 'readOnly', 'openExisting');

    // Assume the file we are reading contains the following text:
    // abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
    // (in ANSI format -- i.e. one byte per char).

    // Read 26 bytes:
    $sText = $sftp->ReadFileText($handle, 26, 'ansi');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Should print "abcdefghijklmnopqrstuvwxyz";
echo $sText, "\n";

// Read the next 10 bytes.
try {
    $sText = $sftp->ReadFileText($handle, 10, 'ansi');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Should print "1234567890";
echo $sText, "\n";

// Read the next 26 bytes.
try {
    $sText = $sftp->ReadFileText($handle, 26, 'ansi');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Should print "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
echo $sText, "\n";

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

echo "Success.\n";