Dan Nite
Dan Nite

Reputation: 79

PHP - reading FTP file without downloading it/saving it locally

I would like to get FTP files content without saving it locally.

This is what I have so far:

$ftp_server = "my_server";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to the server");

if (@ftp_login($ftp_conn, "username", "password")) {

    $local_file = 'C:\Users\user\Desktop\testing.txt';
    $fp = fopen($local_file, "w");

    $d = ftp_nb_fget($ftp_conn, $fp, "commands.yml", FTP_BINARY);

    while ($d == FTP_MOREDATA) {
        $d = ftp_nb_continue($ftp_conn);
    }

    if ($d != FTP_FINISHED) {
        echo "Error downloading $server_file";
        exit(1);
    }

    ftp_close($ftp_conn);
    fclose($fp);

    $filename = 'C:\Users\user\Desktop\testing.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);

    echo $contents;

} else {
    echo "Couldn't establish a connection.";
}

The code above saves the file and read the file content. Is it possible to read the file without saving it locally?

Upvotes: 1

Views: 2347

Answers (1)

user557846
user557846

Reputation:

From the answer on the official PHP site from bob at notallhere dot com:

Don't want to use an intermediate file? Use 'php://output' as the filename and then capture the output using output buffering.

ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();

Upvotes: 4

Related Questions