Access/Download server files, not in site root, with PHP

Posted by user271619 on Stack Overflow See other posts from Stack Overflow or by user271619
Published on 2010-04-05T23:08:42Z Indexed on 2010/04/05 23:13 UTC
Read the original article Hit count: 305

Filed under:
|

Usually I save documents (images, mpegs, excel, word docs, etc...) for my friends or family on my website's root, inside a directory called /files/ or something similar. Nothing too uncommon.

But, I have been playing with user session control, and allowing users to upload files to the dedicated /files/ directory. (the file names are saved in a db, with that user's ID)

But, that means other people could try to guess and locate other people's files.
I do randomize the file names, upon upload. And I stop the apache from displaying the /files/ directory content.

However, I'd like to start saving the files outside of the website's root. This way it can't be accessible via the browser.

I don't have any code to show, but I didn't want to even start on this endeavor if it's not able to be accomplished. I did find this snippet that shows how to display an image, from outside your website root:

$file = $_GET['file'];
$fileDir = '/path/to/files/';

if (file_exists($fileDir . $file))
{
    // Note: You should probably do some more checks 
    // on the filetype, size, etc.
    $contents = file_get_contents($fileDir . $file);

    // Note: You should probably implement some kind 
    // of check on filetype
    header('Content-type: image/jpeg');

    echo $contents;
}

?>

Maybe I can use this for any file type, but has anyone heard of a better way to allow users (logged in) to access their files from online, but not letting other users has similar access?

© Stack Overflow or respective owner

Related posts about php

Related posts about file-get-contents