What are the best practices for handling email attachments in PHP, specifically when dealing with PDF files?

When handling email attachments in PHP, especially PDF files, it is important to validate and sanitize the file before processing it to prevent security vulnerabilities like malicious code execution. One way to do this is by checking the file extension and mime type to ensure it is a valid PDF file. Additionally, consider storing the uploaded files in a secure directory outside of the web root to prevent direct access.

// Example code snippet for handling email attachments in PHP with PDF files

// Check if the uploaded file is a PDF
if ($_FILES['attachment']['type'] == 'application/pdf' && pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION) == 'pdf') {
    $uploadDir = '/path/to/secure/directory/';
    $uploadFile = $uploadDir . basename($_FILES['attachment']['name']);

    // Move the uploaded file to a secure directory
    if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadFile)) {
        echo 'File is a valid PDF and has been uploaded successfully.';
    } else {
        echo 'Failed to upload file.';
    }
} else {
    echo 'Invalid file type. Please upload a PDF file.';
}