How can PHP be used to prevent file download links from being shared on other websites?

File download links can be prevented from being shared on other websites by implementing a mechanism that checks the HTTP referer header of the request. This header contains the URL of the page making the request, so by verifying that the request is coming from the same website, we can restrict access to the file. Below is a PHP code snippet that demonstrates how this can be achieved:

<?php
// Check if the request is coming from the same website
if(isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) {
    // Allow file download
    // Add code to serve the file here
} else {
    // Redirect or display an error message
    header('Location: /error-page.php');
    exit();
}
?>