What are the best practices for integrating email sending functionality with file upload functionality in PHP scripts?

When integrating email sending functionality with file upload functionality in PHP scripts, it is important to ensure that the file is properly uploaded and attached to the email before sending. One best practice is to first handle the file upload, validate it, and then store it in a temporary location on the server. Once the file is successfully uploaded, you can then attach it to the email before sending it out.

// Handle file upload
if(isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK){
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_type = $_FILES['file']['type'];
    
    // Validate file type and size here
    
    $file_path = 'uploads/' . $file_name;
    move_uploaded_file($file_tmp, $file_path);
    
    // Email sending functionality
    $to = 'recipient@example.com';
    $subject = 'File Attachment';
    $message = 'Please find the attached file.';
    $headers = 'From: sender@example.com';
    
    $file = $file_path;
    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));
    
    $attachment = "Content-Type: application/octet-stream; name=\"" . basename($file) . "\"\r\n";
    $attachment .= "Content-Transfer-Encoding: base64\r\n";
    $attachment .= "Content-Disposition: attachment\r\n\r\n";
    $attachment .= $content . "\r\n";
    
    $result = mail($to, $subject, $message, $headers . "\r\n" . $attachment);
    
    if($result){
        echo 'Email sent successfully with file attachment.';
    } else {
        echo 'Failed to send email with file attachment.';
    }
}