PHP Function Reference

PHP ftp_nb_fput() Function



The PHP ftp_nb_fput() function uploads from an open local file and saves it to a file on the FTP server (non-blocking).

The difference between this function and ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Syntax

ftp_nb_fput(ftp, server_file, open_file, 
             mode, offset)

Parameters

ftp Required. Specify the FTP connection to use.
server_file Required. Specify the server file path to upload to.
open_file Required. Specify the an open file pointer. Reading stops at end of file.
mode Optional. Specify the transfer mode. Must be either FTP_ASCII or FTP_BINARY.
offset Optional. Specify the position in the remote file to start uploading to.

Return Value

Returns any of the following values:

  • FTP_FAILED: Asynchronous transfer has failed.
  • FTP_FINISHED: Asynchronous transfer has finished.
  • FTP_MOREDATA: Asynchronous transfer is still active.

Example:

The example below shows the usage of ftp_nb_fput() function.

<?php
//FTP server to use
$ftp_server = "ftp.example.com";
 
//username for the FTP Connection
$ftp_user = "user";
  
//password for the user
$ftp_pass = "password";
  
//set up a connection or die 
$ftp = ftp_connect($ftp_server)
    or die("Could not connect to $ftp_server");
   
if($ftp) {
  echo "Successfully connected to $ftp_server!\n";
 
  //trying to login
  if(@ftp_login($ftp, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";

    //server file path where the 
    //file need to be uploaded
    $server_file = "server_demo.txt";

    //local open file pointer
    $open_file = fopen("local_demo.txt", "w");
        
    //uploading from an open local file and 
    //saves it to a file on the FTP server
    $ret = ftp_nb_fput($ftp, $server_file, 
                        $open_file, FTP_ASCII);

    while ($ret == FTP_MOREDATA) {
      //continue uploading...
      $ret = ftp_nb_continue($ftp);
    }

    if ($ret == FTP_FINISHED) {
      echo "Successfully uploaded $open_file\n";
    } else {
      echo "Error while uploading $open_file\n";
      exit(1);
    }

    //closing the file pointer
    fclose($open_file);
    
  } else {
    echo "Couldn't connect as $ftp_user\n";
  }
 
  //close the connection
  if(ftp_close($ftp)) {
    echo "Connection closed successfully!\n"; 
  } 
}
?>

The output of the above code will be:

Successfully connected to ftp.example.com!
Connected as user@ftp.example.com
Successfully uploaded local_demo.txt
Connection closed successfully!

❮ PHP FTP Reference