What are some best practices for handling file permissions and file downloads in PHP scripts?

When handling file permissions and file downloads in PHP scripts, it is important to ensure that only authorized users have access to the files and that the files are downloaded securely. One best practice is to store files outside of the web root directory to prevent direct access. Additionally, use PHP's file permission functions to set appropriate permissions for the files.

// Set appropriate file permissions
chmod($filePath, 0644);

// Check if user is authorized to download the file
if ($userIsAuthorized) {
    // Set appropriate headers for file download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Content-Length: ' . filesize($filePath));

    // Output the file content
    readfile($filePath);
} else {
    // Handle unauthorized access
    echo "You are not authorized to download this file.";
}