What is the best practice for handling file uploads in multi-page forms in PHP?
When handling file uploads in multi-page forms in PHP, it is best practice to store the uploaded file temporarily on the server and pass the file information (such as file name and path) between form pages using sessions or hidden input fields. This ensures that the file is not lost when navigating between form pages and allows for proper validation and processing of the file at the final form submission.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
$tempFilePath = $file['tmp_name'];
$fileName = $file['name'];
$_SESSION['tempFilePath'] = $tempFilePath;
$_SESSION['fileName'] = $fileName;
// Move the temporary file to a desired directory
move_uploaded_file($tempFilePath, 'uploads/' . $fileName);
// Redirect to the next form page
header('Location: next_form_page.php');
exit;
}
?>