What best practices should be followed when dynamically creating and offering files for download in PHP without refreshing the page?

When dynamically creating and offering files for download in PHP without refreshing the page, it is important to use AJAX to handle the file creation and download process asynchronously. This ensures a seamless user experience without the need to refresh the page. Additionally, it is recommended to set the appropriate headers for file downloads to ensure the file is downloaded correctly.

<?php
// Check if the request is an AJAX request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Generate the file content dynamically
    $fileContent = "Hello, this is a dynamically generated file!";
    
    // Set the appropriate headers for file download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="downloaded-file.txt"');
    
    // Output the file content
    echo $fileContent;
    
    // Terminate the script
    exit;
} else {
    // Handle non-AJAX requests here
    echo "Error: This endpoint only accepts AJAX requests.";
}
?>