What are some best practices for handling email attachments in PHP scripts to ensure smooth functionality?

When handling email attachments in PHP scripts, it is important to validate the file type and size to prevent potential security risks. Additionally, always sanitize the file name to avoid any malicious code execution. Finally, consider storing the attachments in a secure directory outside of the web root to prevent direct access.

// Example code snippet for handling email attachments in PHP scripts

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$maxSize = 5 * 1024 * 1024; // 5MB

if (in_array($_FILES['attachment']['type'], $allowedTypes) && $_FILES['attachment']['size'] <= $maxSize) {
    // Sanitize file name
    $fileName = preg_replace('/[^a-zA-Z0-9\.\-\_]/', '', $_FILES['attachment']['name']);

    // Store attachment in a secure directory
    move_uploaded_file($_FILES['attachment']['tmp_name'], '/path/to/secure/directory/' . $fileName);
} else {
    echo 'Invalid file type or size.';
}