How can PHP scripts be used to authenticate users before allowing access to specific files for download?
To authenticate users before allowing access to specific files for download, you can create a PHP script that checks the user's credentials before serving the file. This can be done by verifying the user's login information against a database or other authentication method. Once the user is authenticated, the script can then serve the file for download.
<?php
// Check if user is logged in
session_start();
if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header('Location: login.php');
exit;
}
// Check if user has permission to download file
$allowed_users = ['user1', 'user2']; // List of users allowed to download
$current_user = $_SESSION['username']; // Get current user
if(!in_array($current_user, $allowed_users)) {
die('You do not have permission to access this file.');
}
// Serve the file for download
$file_path = 'path/to/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile($file_path);
?>
Keywords
Related Questions
- What is the significance of the error message "Notice: Undefined offset" in PHP and how can it impact the functionality of a script?
- What potential issue is identified in the MySQL query regarding the 'status' field?
- What are the advantages and disadvantages of passing user credentials through GET or POST requests in PHP?