What are the potential pitfalls of saving files on the server before offering them for download in PHP?

Potential pitfalls of saving files on the server before offering them for download in PHP include security vulnerabilities, increased server storage usage, and potential file overwrite issues. To solve this, you can directly output the file to the user without saving it on the server by using the appropriate headers and readfile() function.

<?php
$file = 'path/to/file.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}
?>