Christian Bundgaard
Christian Bundgaard

Reputation: 243

Deny access to files in folder - allow acces from one file

I have a folder, /songs. All files inside this folder should be unaccessible. That should be easy to do.

But I want ONE file, player.php to have access to them. How can I do this?

I suppose .htaccess is the way to go.

Upvotes: 1

Views: 190

Answers (1)

Jon Lin
Jon Lin

Reputation: 143966

There's two ways to go about doing this, you can either make the files completely inaccessible from the internet or you can check the referer (sic).

The HTTP Referer is a request header field that is sometimes included with a request telling the web server where the request was referred from. For example, a page index.html could have an image <img src="/foo.png">. When the browser loads index.html and sees the image, it'll also load the image. The request made for the image will include http://example.com/index.html as the referer before that page is what referred the browser to load the image. The problem with the referer is that (like most HTTP request headers) it can be easily forged. This means that someone who wants to download all of your songs can just fake the referer to say it came from player.php. This is probably the easiest to implement:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !/player\.php
RewriteCond $1 !player\.php
RewriteRule ^songs/(.*)$ - [L,F]

Those rules would go in the htaccess file in your document root. Or if you want to put it in the songs folder, remove the songs/ part of the rule's regular expression.

The first solution is the best because it makes it so the files are inaccessible except through a script of your design. So something like (we'll call it load.php):

<?php

// make whatever checks here to ensure it's ok to send the file to the browser

$name = $_GET['name'];
$fp = fopen($name, 'rb');

// Change the header to whatever your file's mime type is
header("Content-Type: audio/mp3");
header("Content-Length: " . filesize($name));

fpassthru($fp);
exit;

?>

Then you can access those files by going to: http://example.com/load.php?name=song.mp3. As for what checks you need to do, you can check the referer by looking at $_SERVER['HTTP_REFERER']. You can set a UUID or session cookie from player.php and then check it in load.php.

Then you can deny access to your files using something like:

RewriteEngine On
RewriteCond $1 !(player|load)\.php
RewriteRule ^songs/(.*)$ - [L,F]

to deny access to anything that isn't player.php or load.php

Upvotes: 1

Related Questions