What are best practices for managing sessions in PHP scripts to allow for multiple image uploads while preventing unnecessary duplicates?

When managing sessions in PHP scripts for multiple image uploads, it is important to generate unique identifiers for each uploaded image and store them in the session. This way, you can prevent unnecessary duplicates by checking if an image with the same identifier has already been uploaded. Additionally, you should handle the file upload process securely to prevent any potential security risks.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $file = $_FILES['image'];
    $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $uniqueIdentifier = uniqid() . '.' . $fileExtension;

    if (!isset($_SESSION['uploaded_images'])) {
        $_SESSION['uploaded_images'] = [];
    }

    if (!in_array($uniqueIdentifier, $_SESSION['uploaded_images'])) {
        move_uploaded_file($file['tmp_name'], 'uploads/' . $uniqueIdentifier);
        $_SESSION['uploaded_images'][] = $uniqueIdentifier;
    }
}
?>