Skip to content
PHP Logo

How can sessions be used to store IDs for multiple file uploads in PHP?

When uploading multiple files in PHP, it can be useful to store the IDs of the uploaded files in a session variable to keep track of them. This allows you to easily retrieve the IDs later in the session without having to pass them around in URLs or hidden form fields. To implement this, you can generate a unique ID for each uploaded file, store these IDs in an array in the session, and then access them as needed throughout the session.

php
// Start the session
session_start();

// Check if the session variable for file IDs exists, if not, initialize it as an empty array
if (!isset($_SESSION['file_ids'])) {
    $_SESSION['file_ids'] = [];
}

// Generate a unique ID for the uploaded file
$file_id = uniqid();

// Store the file ID in the session variable
$_SESSION['file_ids'][] = $file_id;

// Retrieve the file IDs from the session
$file_ids = $_SESSION['file_ids'];

// Loop through the file IDs and do something with them
foreach ($file_ids as $file_id) {
    // Do something with the file ID
    echo $file_id . "<br>";
}