Can .htaccess be used in conjunction with PHP to restrict direct file downloads?
Yes, .htaccess can be used in conjunction with PHP to restrict direct file downloads by using the mod_rewrite module to redirect requests for specific file types to a PHP script that can handle access control. The PHP script can then check if the user is authorized to download the file before serving it.
# .htaccess
RewriteEngine On
RewriteRule \.pdf$ download.php [NC,L]
```
```php
// download.php
<?php
// Check if user is authorized to download the file
if($userAuthorized) {
$file = 'path/to/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
} else {
echo 'You are not authorized to download this file.';
}
?>
Keywords
Related Questions
- What are the best practices for avoiding unexpected results in PHP comparisons?
- Are there any specific PHP functions or libraries that can help mitigate the risks associated with allowing user input in iframes?
- How can PHP error reporting and display settings be utilized to troubleshoot image generation issues when using the GD library?