How can PHP be used to prevent unauthorized access to downloadable files on a website?
To prevent unauthorized access to downloadable files on a website, you can use PHP to check if the user is authenticated before allowing them to download the file. This can be achieved by storing the files outside of the web root directory and using PHP to serve the files only to authenticated users.
<?php
// Check if user is authenticated
if (isset($_SESSION['user_id'])) {
$file = '/path/to/downloadable/file.pdf';
// Check if the file exists
if (file_exists($file)) {
// Set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));
// Serve the file
readfile($file);
exit;
} else {
echo 'File not found.';
}
} else {
echo 'Unauthorized access.';
}
?>