What are some alternative approaches to handling file downloads in PHP that do not involve bypassing security measures?

When handling file downloads in PHP, it is important to ensure that security measures are not bypassed to prevent unauthorized access to sensitive files. One alternative approach is to use PHP's readfile() function, which reads a file and sends it to the output buffer. This function ensures that the file is only accessible through the PHP script, maintaining security.

$file = 'path/to/file.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}