What best practices should be followed when handling FTP connections and file management in PHP?

When handling FTP connections and file management in PHP, it is important to follow best practices to ensure security and efficiency. This includes using secure connections (SFTP), sanitizing user input to prevent vulnerabilities like directory traversal attacks, and properly handling errors to avoid exposing sensitive information.

// Example of connecting to an FTP server using secure SFTP and listing files in a directory

// Set up connection details
$ftp_server = 'sftp://example.com';
$ftp_user = 'username';
$ftp_pass = 'password';

// Connect to the FTP server
$conn_id = ftp_connect($ftp_server);

// Login to the FTP server
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);

// Check if the connection was successful
if ($conn_id && $login_result) {
    // Get the list of files in a directory
    $files_list = ftp_nlist($conn_id, '/path/to/directory');

    // Output the list of files
    foreach ($files_list as $file) {
        echo $file . "<br>";
    }

    // Close the FTP connection
    ftp_close($conn_id);
} else {
    echo "Failed to connect to FTP server";
}