What are the best practices for securely handling file uploads and downloads in PHP, especially when sensitive data is involved?

When handling file uploads and downloads in PHP, especially when dealing with sensitive data, it is crucial to implement proper security measures to prevent unauthorized access or malicious attacks. This includes validating file types, restricting file sizes, storing files outside of the web root directory, and using secure file transfer protocols such as HTTPS.

// Example of securely handling file uploads in PHP

// Validate file type
$allowedTypes = ['pdf', 'doc', 'docx'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileType, $allowedTypes)) {
    die("Invalid file type. Only PDF, DOC, and DOCX files are allowed.");
}

// Restrict file size
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die("File size exceeds the limit of 2MB.");
}

// Store file outside of web root directory
$uploadDirectory = '/path/to/uploads/';
$uploadedFilePath = $uploadDirectory . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath);

// Example of securely handling file downloads in PHP

// Set headers for secure file download
$filePath = '/path/to/uploads/example.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($filePath));
header('Content-Length: ' . filesize($filePath));

// Output the file content
readfile($filePath);