What are some best practices for transferring files between servers using FTP in PHP?

When transferring files between servers using FTP in PHP, it is important to ensure that the connection is secure and that the transfer is done efficiently. One best practice is to use passive mode for FTP connections to avoid potential firewall issues. Additionally, it is recommended to handle errors and exceptions properly to ensure the reliability of the file transfer process.

// Connect to the FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$conn_id = ftp_connect($ftp_server);

// Login to the FTP server
if (ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    // Switch to passive mode
    ftp_pasv($conn_id, true);

    // Transfer file from source to destination
    $source_file = 'source_file.txt';
    $destination_file = 'destination_file.txt';
    if (ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY)) {
        echo "File transferred successfully.";
    } else {
        echo "Error transferring file.";
    }

    // Close the FTP connection
    ftp_close($conn_id);
} else {
    echo "Failed to connect to FTP server.";
}