ftp_fput() function in PHP

The ftp_fput() function is used to upload from an open file and saves it to a file on the FTP server. This function reads data from an already opened local file resource and transfers it to a remote file on the FTP server.

Syntax

ftp_fput(connection, remote_file, file_pointer, mode, startpos);

Parameters

  • connection − The FTP connection resource

  • remote_file − The remote file path to upload to

  • file_pointer − An already opened local file resource

  • mode − The transfer mode (FTP_ASCII or FTP_BINARY)

  • startpos − Optional. The position to begin uploading from (default is 0)

Return Value

The ftp_fput() function returns TRUE on success and FALSE on failure.

Example

The following example demonstrates how to upload a local file to an FTP server using an open file pointer −

<?php
    $ftp_server = "192.168.0.4";
    $ftp_user = "amit";
    $ftp_pass = "tywg61gh";
    
    // Connect to FTP server
    $connection = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($connection, $ftp_user, $ftp_pass);
    
    // File details
    $remote_file = "demo.txt";
    $local_file = "new.txt";
    
    // Open local file for reading
    $file_pointer = fopen($local_file, "r");
    
    // Upload file
    if (ftp_fput($connection, $remote_file, $file_pointer, FTP_ASCII)) {
        echo "File uploaded successfully!";
    } else {
        echo "Error in uploading file!";
    }
    
    // Close connections
    fclose($file_pointer);
    ftp_close($connection);
?>

Key Points

  • The local file must be opened with fopen() before using ftp_fput()

  • Use FTP_ASCII for text files and FTP_BINARY for binary files

  • Always close both the file pointer and FTP connection after use

  • The function requires an active FTP connection established with ftp_connect() and ftp_login()

Conclusion

The ftp_fput() function provides an efficient way to upload files to FTP servers using open file resources. It's particularly useful when you need to upload large files or when working with file streams in PHP applications.

Updated on: 2026-03-15T07:39:59+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements