Page 1 of 1

Require login credentials for certain files

Posted: Fri Mar 26, 2010 4:21 am
by Sindarin
I am wondering how would I limit access to certain files inside a directory.

For example we have a user login system with session/cookies which is used to access creating administrator pages. Now there would be a section where the administrator could upload files (images, documents...) which would only be available to certain people (let's say visitors who are registered as members). How could I make it so those files are available to members only and cannot be accessed directly by non-members?

I am thinking of trying something with cmod().

Re: Require login credentials for certain files

Posted: Fri Mar 26, 2010 7:38 am
by requinix
chmod? Don't see how that could help you.

Use some sort of authentication system at the start of those files, such as checking the session for the right stuff and sending a 404 if it isn't there.

Re: Require login credentials for certain files

Posted: Fri Mar 26, 2010 9:55 am
by Alkis
My suggestion is to first have those files put outside the public html directory. This ensures that the files are not accessible be any means.

Then if the user is an authenticated one, using php open the the desired file and output the file using first content type declarations with the header() function (e.g. header('Content-type:....') depends on the type of each file ) use the readfile() function to send the file to the client. Example:

Let's say the site relays on the following directory:
/var/www/mysite/public_html


Set the directory where the files is to be put outside public, e.g.:
$filesDir = '/var/www/mysite/files';

If the user is authenticated then:

Let's say the File to be requested is file01.zip, or maybe an id from a database e.g. FileID : 45.

Using your code, you know the file to be retrieved from the user is the file01.zip, and you set it to the variable $fileName so:

---------------------------
if you want, you cat get information for that file and how to handle it (The following function is very well documented in php manual):

//set the full path of the file on a variable:

$filePath = $filesDir.'/'.$fileName;

$fileInfo = pathInfo[$filePath ];

$extension = $fileInfo['extension']; // you get the extension of the file, in this case 'zip';
------------------------------

prepare the output:

//the following lines (headers) ensures that a download dialog will appear to the user, avoiding him to open the file on the browser (if it was pdf of jpg etc...):
header('Content-Description: File Transfer');
header('Content-Type: application/force-download ');
header('Content-Length: ' . filesize($filePath));
header('Content-Disposition: attachment; filename=' . basename($filePath));

//finally output the contents of the file:
readfile($filePath);