In PHP, what are the best practices for handling file uploads in forms and attaching uploaded files to emails, especially when using functions like mail() or php-mailer?

When handling file uploads in forms and attaching uploaded files to emails in PHP, it is important to ensure proper validation, security measures, and error handling. One recommended approach is to use PHP's built-in functions like move_uploaded_file() to securely move the uploaded file to a designated folder, and then use a library like phpmailer to attach the file to an email.

// Handle file upload
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

// Attach uploaded file to email using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->addAttachment($target_file);
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body    = 'Email body';
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}