How can the PHP code be optimized to ensure a successful FTP connection and file transfer process between two servers?

To optimize the PHP code for a successful FTP connection and file transfer process between two servers, ensure that the FTP functions are properly configured with the correct credentials and server details. Additionally, handle errors effectively to troubleshoot any connection or transfer issues that may arise.

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

// Connect to FTP server
$conn_id = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

// Login to FTP server
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password);
if (!$login_result) {
    die("Login failed");
}

// Transfer file
$local_file = 'local_file.txt';
$remote_file = 'remote_file.txt';
if (ftp_put($conn_id, $remote_file, $local_file, FTP_ASCII)) {
    echo "File transfer successful";
} else {
    echo "File transfer failed";
}

// Close FTP connection
ftp_close($conn_id);