In the context of the provided PHP script, what are some alternative approaches to achieving the desired functionality of displaying email attachments on a webpage without compromising security?

The issue with the provided PHP script is that it directly exposes email attachments to the web, potentially compromising security. To solve this, a more secure approach would be to store the attachments outside of the web root directory and serve them through a PHP script that verifies the user's access rights before allowing download.

<?php
// Code to store email attachments outside web root directory
$attachmentDirectory = '/path/to/attachment/directory/';

// Code to fetch attachment file name from email
$attachmentFileName = 'attachment.pdf';

// Code to check user's access rights before serving attachment
if (userHasAccessRights()) {
    $attachmentPath = $attachmentDirectory . $attachmentFileName;
    
    // Code to serve attachment file
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="' . $attachmentFileName . '"');
    readfile($attachmentPath);
} else {
    // Code to handle unauthorized access
    echo 'You do not have permission to access this file.';
}

function userHasAccessRights() {
    // Code to check user's access rights, return true if user has access
    return true;
}
?>