What are some best practices for implementing a file upload feature in a PHP contact form?

When implementing a file upload feature in a PHP contact form, it is important to ensure that the server can handle file uploads securely and efficiently. Best practices include validating file types and sizes, storing uploaded files in a secure directory outside of the web root, and sanitizing file names to prevent malicious attacks.

<?php
// Check if a file has been uploaded
if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    // Validate file type
    $fileType = pathinfo($uploadFile, PATHINFO_EXTENSION);
    if(in_array($fileType, ['jpg', 'jpeg', 'png', 'pdf'])) {
        // Move the uploaded file to a secure directory
        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type. Allowed types: jpg, jpeg, png, pdf.';
    }
}
?>