How can PHP be used to generate one-time valid download links for large files on a website?

Generating one-time valid download links for large files on a website can be achieved by creating a unique token for each download request and associating it with the specific file. This token can be validated when the user tries to access the download link, ensuring that it can only be used once. Below is a PHP code snippet that demonstrates how to implement this functionality.

<?php
// Generate a unique token for the download link
$token = md5(uniqid(rand(), true));

// Store the token in a database or session along with the file path
$_SESSION['download_tokens'][$token] = 'path/to/large_file.zip';

// Generate the download link with the token
$download_link = 'http://example.com/download.php?token=' . $token;

// Redirect the user to the download link
header('Location: ' . $download_link);
exit;

// In download.php file
session_start();

// Validate the token and retrieve the file path
if(isset($_GET['token']) && isset($_SESSION['download_tokens'][$_GET['token']])) {
    $file_path = $_SESSION['download_tokens'][$_GET['token']];
    
    // Serve the file for download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    readfile($file_path);
    
    // Remove the token to make it one-time use
    unset($_SESSION['download_tokens'][$_GET['token']]);
    exit;
} else {
    echo 'Invalid token';
}
?>