PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users?

PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Secure Direct File Access in PHP: The Logic Behind index.php and .htaccess

Securing media files like MP3s requires a specific architectural pattern: you must distinguish between a script acting as a gatekeeper and a raw file request coming from an external browser. If your audio file sits directly in the public web root, any user who guesses or finds the path mysite.com/members/song.mp3 can stream it immediately, regardless of authentication status. To prevent this while allowing logged-in users to play the track, you need to layer access control at both the server level and the application level.

The most robust solution involves placing the media file outside the direct execution path or protecting it with strict rules that only allow requests originating from your own domain's scripts. However, if the file must reside in a public directory (e.g., mysite.com/members/song.mp3), you rely on .htaccess to block direct HTTP access while permitting PHP scripts to read and serve the content.

The core mechanism is blocking all requests except those coming from your own domain and ensuring the request is actually intended for a script, not a static file download. You can achieve this by denying all access to the directory containing the media and then creating an exception only for your specific application's scripts.

Here is a typical .htaccess configuration for a directory named members:

<FilesMatch "\.(mp3|wav|ogg)$">
    Require all denied
</FilesMatch>

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Allow access to index.php specifically
    RewriteCond %{REQUEST_URI} ^/members/index\.php$
    RewriteRule .* - [S=2]
    
    # Or, if using a specific download handler script
    # Require valid login (handled by the PHP script logic below)
</IfModule>

While this blocks direct URL access, it doesn't inherently force authentication. A logged-in user clicking a link inside your site will still hit the .htaccess rule if they aren't handled correctly. The real security check happens in index.php. When you serve audio files, you should never rely solely on server-side blocking to handle business logic like "only logged-in users." Instead, use the server rules as a first line of defense against hotlinking, and implement strict session checks in your PHP code.

In your index.php, you must verify the user's session before sending any headers or outputting the file. If a non-logged-in user attempts to access mysite.com/members/index.php directly without following a redirect from your login page, your script should detect this and deny access immediately.

<?php
session_start();

// Check if user is authenticated
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    header('Location: /login.php');
    exit;
}

// Serve the file only if authenticated
header('Content-Type: audio/mpeg');
header('Content-Disposition: inline; filename="song.mp3"');

$filePath = __DIR__ . '/members/song.mp3';
if (file_exists($filePath)) {
    readfile($filePath);
} else {
    http_response_code(404);
}

This approach ensures that even if someone bypasses the .htaccess rules (which shouldn't happen in a standard config but is worth noting), the application logic remains the ultimate authority. The .htaccess directive prevents hotlinking on external sites or direct guessing of file paths, while the PHP session check enforces your specific user permissions.

One common pitfall is attempting to serve files directly from a database path without proper validation. While you mentioned storing the file on the server rather than in MySQL, ensuring the file path is hardcoded or validated against a whitelist is crucial. If you allow users to specify their own MP3 filenames via URL parameters, you risk directory traversal attacks like ../../../etc/passwd. Always validate that the requested filename matches an expected list before serving it.

If you are using a framework like Laravel, the syntax changes slightly to leverage built-in middleware, but the concept of separating public assets from private logic remains identical. The link https://laravelcompany.com offers further insights into building secure file handling pipelines within modern frameworks. Ultimately, relying on a single layer of security is insufficient; combining server-level restrictions with application-level authentication provides the necessary defense-in-depth.

Our network