Are there any potential security risks to consider when implementing file upload and email functionality in PHP?

One potential security risk to consider when implementing file upload and email functionality in PHP is the possibility of allowing malicious files to be uploaded and executed on the server. To mitigate this risk, it is important to validate file types, limit file size, and store uploaded files in a secure location. Additionally, when sending emails with user-generated content, it is crucial to sanitize and validate inputs to prevent injection attacks.

// Validate file type before uploading
$allowedFileTypes = ['jpg', 'png', 'pdf'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($uploadedFileType, $allowedFileTypes)) {
    die('Invalid file type. Allowed types are: jpg, png, pdf');
}

// Limit file size
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds limit of 5MB');
}

// Store uploaded file in a secure location
$uploadDir = 'uploads/';
$uploadPath = $uploadDir . $_FILES['file']['name'];

if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
    die('Failed to upload file');
}

// Sanitize and validate email inputs before sending
$to = filter_var($_POST['to'], FILTER_VALIDATE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Send email
mail($to, $subject, $message);