What are the best practices for handling file downloads in PHP to avoid data corruption or premature file endings?

When handling file downloads in PHP, it is important to set appropriate headers to ensure the file is downloaded correctly without data corruption or premature file endings. This can be achieved by setting the Content-Type header to the correct MIME type of the file and using the Content-Disposition header to specify the filename. Additionally, using readfile() function to read and output the file content in chunks can help prevent memory issues with large files.

// Set headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.txt"');

// Read and output file content in chunks
readfile('path/to/example.txt');