How can PHP developers ensure the security of file downloads initiated by their code?

PHP developers can ensure the security of file downloads initiated by their code by implementing proper access control measures, validating user input, sanitizing file paths, and using secure download links with a one-time token to prevent unauthorized access.

<?php
// Validate user input for file path
$file = 'path/to/file.pdf';

// Check if the file exists and is within a safe directory
if (file_exists($file) && strpos(realpath($file), '/safe_directory/') === 0) {
    // Generate a one-time token for the download link
    $token = md5(uniqid(rand(), true));
    
    // Store the token in a session or database for verification
    $_SESSION['download_token'] = $token;
    
    // Create a secure download link with the token
    $download_link = 'download.php?file=' . urlencode($file) . '&token=' . $token;
    
    // Redirect the user to the secure download link
    header('Location: ' . $download_link);
    exit;
} else {
    // Handle error or redirect to a safe page
    echo 'File not found or invalid path.';
}
?>