What are some best practices for securely uploading and downloading PDF files using PHP?

When uploading and downloading PDF files using PHP, it is important to ensure that the files are securely handled to prevent unauthorized access or malicious attacks. Some best practices include validating file types, setting proper file permissions, using secure file storage locations, and implementing measures such as file hashing or encryption.

// Securely upload PDF file
$uploadDir = 'uploads/';
$allowedTypes = ['application/pdf'];

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileType = mime_content_type($_FILES['file']['tmp_name']);
    
    if (in_array($fileType, $allowedTypes)) {
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $_FILES['file']['name']);
        echo 'File uploaded successfully!';
    } else {
        echo 'Invalid file type. Please upload a PDF file.';
    }
}

// Securely download PDF file
$filePath = 'uploads/example.pdf';

if (file_exists($filePath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    readfile($filePath);
} else {
    echo 'File not found.';
}