What are the best practices for initiating file downloads through PHP to ensure user authentication?
When initiating file downloads through PHP, it is essential to ensure user authentication to prevent unauthorized access to sensitive files. One way to achieve this is by using session variables to validate the user's credentials before allowing the download to proceed. By checking the user's authentication status before serving the file, you can ensure that only authorized users can access the downloadable content.
<?php
session_start();
// Check if user is authenticated
if(isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true) {
// File path
$file = 'path/to/file.pdf';
// Set headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
// Flush the output buffer
ob_clean();
flush();
// Read the file and output it to the browser
readfile($file);
} else {
// Redirect to login page if user is not authenticated
header('Location: login.php');
exit();
}
?>