How can user authentication be implemented to restrict access to downloads in PHP?
To restrict access to downloads in PHP, user authentication can be implemented by checking if the user is logged in before allowing them to download files. This can be achieved by storing user login information in sessions and verifying it before serving the download file.
<?php
session_start();
// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
// Redirect to login page or display an error message
header('Location: login.php');
exit();
}
// Serve the download file if user is authenticated
$file = 'path/to/download/file.zip';
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
?>