How can the PHP script for FTP file transfers be optimized for better readability and maintainability?

To optimize the PHP script for FTP file transfers for better readability and maintainability, we can break down the code into smaller, reusable functions and add comments to explain the logic. This will make the code easier to understand and maintain.

<?php

// Function to connect to FTP server
function connectToFtp($server, $username, $password) {
    $ftpConnection = ftp_connect($server);
    ftp_login($ftpConnection, $username, $password);
    return $ftpConnection;
}

// Function to upload a file to FTP server
function uploadFileToFtp($ftpConnection, $localFile, $remoteFile) {
    ftp_put($ftpConnection, $remoteFile, $localFile, FTP_BINARY);
}

// Function to disconnect from FTP server
function disconnectFromFtp($ftpConnection) {
    ftp_close($ftpConnection);
}

// FTP server details
$server = 'ftp.example.com';
$username = 'username';
$password = 'password';

// Local and remote file paths
$localFile = 'local_file.txt';
$remoteFile = 'remote_file.txt';

// Connect to FTP server
$ftpConnection = connectToFtp($server, $username, $password);

// Upload file to FTP server
uploadFileToFtp($ftpConnection, $localFile, $remoteFile);

// Disconnect from FTP server
disconnectFromFtp($ftpConnection);

?>