ftp_nb_fget() function in PHP

The ftp_nb_fget() function downloads a file from the FTP server and saves it into an open file pointer. The "nb" stands for "non-blocking", meaning the function can be executed in steps to avoid blocking the script during large file transfers.

Syntax

ftp_nb_fget(con, open_file, server_file, transfer_mode, beg_pos);

Parameters

  • con − The FTP connection resource

  • open_file − The open file pointer where local data is stored

  • server_file − The server file path to download

  • transfer_mode − The transfer mode (FTP_ASCII or FTP_BINARY)

  • beg_pos − Optional. The position to begin downloading (default is 0)

Return Value

The ftp_nb_fget() function returns one of the following constants ?

  • FTP_FAILED − Transfer failed

  • FTP_FINISHED − Transfer completed successfully

  • FTP_MOREDATA − Transfer in progress, more data expected

Example

The following example demonstrates non-blocking FTP file download with progress monitoring ?

<?php
    $ftp_server = "192.168.0.4";
    $ftp_user = "jacob";
    $ftp_pass = "tywg61gh";
    
    $con = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($con, $ftp_user, $ftp_pass);
    
    $my_serverfile = "demo.txt";
    $local_file = "new.txt";
    $file_pointer = fopen($local_file, "w");
    
    $c = ftp_nb_fget($con, $file_pointer, $my_serverfile, FTP_BINARY);
    
    while ($c == FTP_MOREDATA) {
        // Continue downloading
        echo "Downloading...<br>";
        $c = ftp_nb_continue($con);
    }
    
    if ($c != FTP_FINISHED) {
        echo "Error downloading the server file!";
        exit(1);
    }
    
    echo "File downloaded successfully!";
    
    // Close connections
    ftp_close($con);
    fclose($file_pointer);
?>

How It Works

The function initiates a non-blocking download, returning immediately with a status code. Use ftp_nb_continue() in a loop to continue the transfer until completion or failure.

Conclusion

The ftp_nb_fget() function provides non-blocking FTP file downloads, allowing your script to perform other operations while the transfer progresses. Always use ftp_nb_continue() to monitor and complete the transfer.

Updated on: 2026-03-15T07:40:45+05:30

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements