What best practices should be followed when handling file uploads in PHP, especially when dealing with form submissions?

When handling file uploads in PHP, it is important to validate the file type and size to prevent malicious uploads and server overload. Additionally, always store uploaded files outside of the web root directory to prevent direct access. Finally, sanitize file names to avoid any potential security vulnerabilities.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png'];
    if (!in_array($file['type'], $allowedTypes)) {
        die('Invalid file type.');
    }

    // Validate file size
    $maxFileSize = 1048576; // 1MB
    if ($file['size'] > $maxFileSize) {
        die('File is too large.');
    }

    // Store uploaded file outside of web root
    $uploadPath = '/var/www/uploads/' . basename($file['name']);
    move_uploaded_file($file['tmp_name'], $uploadPath);

    // Sanitize file name
    $safeFileName = preg_replace("/[^A-Za-z0-9.]/", '', $file['name']);
}
?>