How can PHP developers securely store and retrieve files like PDFs in a protected environment without exposing them to unauthorized access?
To securely store and retrieve files like PDFs in a protected environment without exposing them to unauthorized access, PHP developers can store the files outside of the web root directory, implement proper authentication and authorization checks before serving the files, and use PHP's built-in functions for file handling with appropriate permissions.
<?php
// Define the directory to store PDF files
$uploadDirectory = '/path/to/protected/directory/';
// Check if user is authenticated and authorized to access the file
if ($authenticated && $authorized) {
// Retrieve the file requested by the user
$file = $_GET['file'];
$filePath = $uploadDirectory . $file;
// Serve the file if it exists and is a PDF
if (file_exists($filePath) && pathinfo($filePath, PATHINFO_EXTENSION) === 'pdf') {
header('Content-Type: application/pdf');
readfile($filePath);
} else {
echo 'File not found or invalid format.';
}
} else {
echo 'Unauthorized access.';
}
?>
Related Questions
- How can PHP be used to read, modify, and write specific sections of a file, such as an HTML table?
- How can you perform a LIKE comparison in PHP similar to SQL queries?
- How can the condition for string length be correctly implemented in PHP to display an error message if the length is not equal to a specific value?