What are some best practices for handling document extraction and display in PHP to ensure efficiency and security?

When handling document extraction and display in PHP, it is important to ensure efficiency and security by properly sanitizing input data, validating file types, and implementing proper error handling. One way to achieve this is by using PHP's built-in functions like `file_get_contents()` and `header()` to securely extract and display documents.

// Example code snippet for handling document extraction and display in PHP

// Validate input data
if(isset($_GET['file']) && is_string($_GET['file'])) {
    $file = $_GET['file'];
    
    // Check if file exists and is a valid type
    if(file_exists($file) && in_array(pathinfo($file, PATHINFO_EXTENSION), ['pdf', 'docx', 'txt'])) {
        
        // Set appropriate headers for file type
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
        
        // Output file contents
        readfile($file);
        exit;
    } else {
        echo "Invalid file type or file does not exist.";
    }
} else {
    echo "Invalid input data.";
}