What are some best practices for handling FTP connections securely in PHP?

When handling FTP connections securely in PHP, it is important to use secure FTP protocols such as FTPS or SFTP instead of plain FTP to encrypt data transmission. Additionally, always validate user input to prevent any potential security vulnerabilities. It is also recommended to use strong passwords and keep them secure.

// Example of connecting to an FTP server securely using FTPS
$ftp_server = 'ftp.example.com';
$ftp_username = 'username';
$ftp_password = 'password';

// Connect using FTPS
$conn_id = ftp_ssl_connect($ftp_server);

// Login to the FTP server
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password);

if ($conn_id && $login_result) {
    echo "Connected to $ftp_server via FTPS";
} else {
    echo "Failed to connect to $ftp_server";
}

// Close the FTP connection
ftp_close($conn_id);