What are some alternative methods to retain file upload data after a page reload in PHP, considering security concerns?

When a file is uploaded in PHP and the page is reloaded, the file data is typically lost. To retain the file upload data after a page reload, one alternative method is to store the file temporarily on the server and then retrieve it upon page reload. This can be done by saving the file in a temporary directory and storing its path in a session variable. However, security concerns arise when dealing with file uploads, so it is important to validate and sanitize the file before storing it, and to restrict access to the temporary directory.

// Start the session
session_start();

// Check if a file has been uploaded
if(isset($_FILES['file'])){
    // Validate and sanitize the uploaded file
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    
    // Move the file to a temporary directory
    $temp_dir = 'temp_files/';
    move_uploaded_file($file_tmp, $temp_dir . $file_name);
    
    // Store the file path in a session variable
    $_SESSION['file_path'] = $temp_dir . $file_name;
}

// Retrieve the file path from the session
if(isset($_SESSION['file_path'])){
    $file_path = $_SESSION['file_path'];
    
    // Display the file upload form with the file path
    echo '<form method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="Upload">
          </form>';
    
    echo '<p>Uploaded file: <a href="'.$file_path.'">'.$file_path.'</a></p>';
}