What is the best practice for offering downloadable files on a website using PHP?
When offering downloadable files on a website using PHP, it is important to ensure that the files are served securely and efficiently. One common approach is to use PHP to handle the file downloads by verifying user permissions and setting appropriate headers to force the browser to download the file instead of displaying it in the browser window.
<?php
// Check if the user is logged in and has permission to download the file
if($user_logged_in && $user_has_permission) {
$file_path = 'path/to/your/file.pdf'; // Path to the file to be downloaded
// Set headers to force download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
header('Content-Length: ' . filesize($file_path));
// Output the file
readfile($file_path);
exit;
} else {
// Handle unauthorized access
echo 'You are not authorized to download this file.';
}
?>