Overview
A file stored under a public web directory may be reachable by anyone who knows or guesses its URL. For invoices, exports, personal documents or generated reports, keep files outside the document root and serve them through an authenticated controller.
Separate storage from public assets
Use a private storage directory with restrictive permissions. Store a generated storage key or relative path in the database, not an arbitrary filesystem path supplied by the browser. Normalize and validate any stored path before opening it.
Authorize every download
A random filename is not an authorization system. Confirm that the current user is allowed to access the requested record and file. Apply the same access policy used by the rest of the application.
$file = $repository->findDownload($downloadId);
if (!$file || !$policy->mayDownload($currentUser, $file)) {
http_response_code(404);
exit;
}
$path = $storageRoot . DIRECTORY_SEPARATOR . $file->storageName;
if (!is_file($path) || !is_readable($path)) {
http_response_code(404);
exit;
}
The repository and policy are application-specific. The storage name should be generated by the server and constrained to a safe format.
Set response headers carefully
Use a server-determined content type where possible, a safe download filename and Content-Disposition: attachment for files intended to be downloaded. Prevent path disclosure in error messages. Consider X-Content-Type-Options: nosniff and appropriate cache controls for sensitive files.
Stream large files
Avoid reading a very large file entirely into PHP memory. Stream it in chunks or delegate delivery to a web-server feature such as X-Sendfile or an internal redirect, configured so the private path cannot be requested directly by the client.
Checklist
- Store private files outside the document root.
- Generate storage names server-side.
- Authorize every request.
- Never accept raw filesystem paths from users.
- Set safe content and cache headers.
- Stream large files efficiently.
- Log access metadata without logging file contents.