Are there any best practices for validating and handling file uploads in PHP to prevent security vulnerabilities?

When handling file uploads in PHP, it is important to validate the file type, size, and content to prevent security vulnerabilities such as file injection or execution. One best practice is to use the `move_uploaded_file` function along with checking the file type using `$_FILES['file']['type']` and validating the file size before saving it to the server.

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $allowedTypes = ['image/jpeg', 'image/png'];
    $maxFileSize = 2 * 1024 * 1024; // 2MB
    
    if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
        $uploadDir = 'uploads/';
        $uploadFile = $uploadDir . basename($_FILES['file']['name']);
        
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}