How can PHP be used to generate time-limited tickets for downloads to prevent hotlinking?

To prevent hotlinking and control access to downloads, PHP can be used to generate time-limited tickets that grant temporary access to the file. This can be achieved by creating a PHP script that generates a unique token or ticket with an expiration time, which can be validated before allowing the download to proceed.

<?php
// Generate a unique ticket with an expiration time
$ticket = md5(uniqid(rand(), true));
$expiration = time() + 3600; // Ticket expires in 1 hour

// Store the ticket and expiration time in a database or session
$_SESSION['download_ticket'] = $ticket;
$_SESSION['download_expiration'] = $expiration;

// Redirect the user to the download link with the ticket as a parameter
header('Location: download.php?ticket=' . $ticket);
?>