What best practices should be followed when using PHP to handle FTP connections and file uploads?

When using PHP to handle FTP connections and file uploads, it is important to follow best practices to ensure security and reliability. This includes validating user input, sanitizing file names, setting appropriate permissions on uploaded files, and using secure FTP protocols such as SFTP. Additionally, it is recommended to handle errors gracefully and implement proper error handling mechanisms.

// Example code snippet for handling FTP connections and file uploads in PHP

// Connect to FTP server using secure SFTP protocol
$ftp_server = 'example.com';
$ftp_username = 'username';
$ftp_password = 'password';
$conn_id = ftp_ssl_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password);

// Check if connection was successful
if (!$conn_id || !$login_result) {
    die('FTP connection failed');
}

// Upload file to FTP server
$local_file = 'local_file.txt';
$remote_file = 'remote_file.txt';
if (ftp_put($conn_id, $remote_file, $local_file, FTP_BINARY)) {
    echo 'File uploaded successfully';
} else {
    echo 'Failed to upload file';
}

// Close FTP connection
ftp_close($conn_id);