What are the best practices for generating and managing unique download links for users in PHP?

Generating and managing unique download links for users in PHP involves creating a secure and unique link for each user to download a specific file. To achieve this, you can generate a unique token for each download link and store it in a database along with the file path. When a user requests a download, check if the token is valid and allow the user to access the file.

<?php
// Generate a unique token
$token = bin2hex(random_bytes(16));

// Store the token and file path in a database
$db = new PDO('mysql:host=localhost;dbname=downloads', 'username', 'password');
$stmt = $db->prepare("INSERT INTO download_links (token, file_path) VALUES (:token, :file_path)");
$stmt->bindParam(':token', $token);
$stmt->bindParam(':file_path', '/path/to/file.pdf');
$stmt->execute();

// Provide the download link to the user
$download_link = "http://example.com/download.php?token=$token";

// Code for download.php
if(isset($_GET['token'])) {
    $token = $_GET['token'];
    
    // Validate the token
    $stmt = $db->prepare("SELECT file_path FROM download_links WHERE token = :token");
    $stmt->bindParam(':token', $token);
    $stmt->execute();
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if($result) {
        $file_path = $result['file_path'];
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
        readfile($file_path);
        exit;
    } else {
        echo "Invalid download link";
    }
}
?>