What are common pitfalls when trying to implement a secure download feature in PHP?

One common pitfall when implementing a secure download feature in PHP is not properly validating the file path before allowing the download. This can lead to potential security vulnerabilities such as directory traversal attacks. To mitigate this risk, always sanitize and validate the file path before serving the file to the user.

<?php

// Validate and sanitize the file path before serving the file
$filePath = '/path/to/secure/file.pdf';

if (strpos($filePath, '/path/to/secure/') !== 0) {
    die('Invalid file path');
}

// Serve the file to the user
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile($filePath);

exit;