What are some best practices for handling different types of attachments in PHP?

When handling different types of attachments in PHP, it is important to properly sanitize and validate the file before processing it. This can be done by checking the file type, size, and content to prevent any malicious files from being uploaded to the server. Additionally, it is recommended to store the attachments in a secure location and provide appropriate error handling in case of any issues.

// Example code for handling file upload in PHP

if ($_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $file_name = $_FILES['attachment']['name'];
    $file_tmp = $_FILES['attachment']['tmp_name'];
    
    // Validate file type
    $file_type = mime_content_type($file_tmp);
    if ($file_type === 'application/pdf') {
        // Process the file
        move_uploaded_file($file_tmp, 'uploads/' . $file_name);
        echo 'File uploaded successfully!';
    } else {
        echo 'Invalid file type. Please upload a PDF file.';
    }
} else {
    echo 'Error uploading file. Please try again.';
}