What are the best practices for handling file operations on an FTP server using PHP?

When handling file operations on an FTP server using PHP, it is important to securely connect to the server, handle errors gracefully, and close the connection after the operation is complete. To ensure secure file transfers, use FTPS (FTP over SSL) or SFTP (SSH File Transfer Protocol) instead of plain FTP.

// Connect to FTP server securely using FTPS
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$ftp_conn = ftp_ssl_connect($ftp_server);

// Login to FTP server
$login = ftp_login($ftp_conn, $ftp_user, $ftp_pass);

// Check if connection is successful
if (!$ftp_conn || !$login) {
    die('FTP connection failed');
}

// Perform file operations here

// Close FTP connection
ftp_close($ftp_conn);