What are common pitfalls in PHP scripts that may result in unexpected file downloads or errors?

Common pitfalls in PHP scripts that may result in unexpected file downloads or errors include not setting the proper content type header before outputting file contents, not handling file paths securely to prevent directory traversal attacks, and not properly sanitizing user input before using it to access files. To prevent unexpected file downloads or errors, always set the content type header to specify the type of content being outputted, use functions like realpath() or basename() to securely handle file paths, and sanitize user input using functions like filter_var() or htmlspecialchars().

// Set the proper content type header
header('Content-Type: application/pdf');

// Securely handle file paths
$filePath = '/path/to/file.pdf';
$realPath = realpath($filePath);

// Sanitize user input
$userInput = $_GET['file'];
$fileName = basename($userInput);