What best practices should be followed when implementing a file download feature in PHP to ensure proper functionality and user experience?

When implementing a file download feature in PHP, it is essential to ensure proper functionality and user experience by following best practices. This includes setting the correct headers to indicate the file type and size, handling errors gracefully, and providing clear instructions to the user. Additionally, it is important to sanitize user input to prevent security vulnerabilities.

<?php
// Get the file path from user input or database
$file_path = '/path/to/file.pdf';

// Check if the file exists
if (file_exists($file_path)) {
    // Set the appropriate headers for file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . basename($file_path));
    header('Content-Length: ' . filesize($file_path));

    // Read the file and output it to the browser
    readfile($file_path);
    exit;
} else {
    // Handle file not found error
    echo 'File not found.';
}
?>