How can PHP be used to protect uploaded files from unauthorized access?
To protect uploaded files from unauthorized access, you can store the files outside the web root directory and use PHP to serve the files only to authorized users. By checking user authentication and permissions before allowing access to the file, you can prevent unauthorized users from accessing sensitive files.
<?php
// Check user authentication and permissions
if($user_authenticated && $user_has_permission) {
$file_path = '/path/to/protected/files/' . $_GET['file'];
if(file_exists($file_path)) {
header('Content-Type: ' . mime_content_type($file_path));
readfile($file_path);
} else {
echo 'File not found.';
}
} else {
echo 'Unauthorized access.';
}
?>