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();
}
?>
Related Questions
- How can the use of __DIR__ in PHP scripts help avoid errors related to file paths and includes?
- In case of issues with form submission in PHP, what debugging techniques or tools can be used to identify and resolve the issue effectively?
- What are best practices for handling pagination in PHP scripts?