Restricting access to files within a specific folder

Is there any way at all to restrict direct access to files within a specific folder to only specific wordpress users that have that specific capability set?

Related posts

Leave a Reply

1 comment

  1. The easiest php solution would be to make a download script. It checks if the user has the right permissions and serves the file to the webclient. Or my preference setup a folder outside your web root and put the files there.

    Set the file permissions with no anonymous access and let the webserver read them and output them in a php file like this. The below code reads the file and sents it to the browser.

    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private",false); 
    header('Content-disposition: attachment; filename='. $file;
    header("Content-Transfer-Encoding:  binary"); 
    header("Content-Length: ". filesize(ABSPATH.$dir.$file); 
    readfile($dir.$file);
    exit();
    

    edit 14-1:

    create a normal upload box and when the file gets uploaded move it to a folder outside of your webroot directory (this folder can not be accessed by users through http, only the webserver.

    if (move_uploaded_file( $_FILES['Filedata']['tmp_name'] , $upload_dir.$filename ) ) {
    // code to do after the file has been copied succesfully. Update your database or something.
    }
    

    $upload_dir.$filename is the full path to the directory outside the www folder.
    The file can now only be accessed by the webserver. Store the location in a database with uploader info. Or create subdirectories for each user. You need something to differentiate the files for each user.

    Now when you want to download a file create a script called download.php
    In that script you check if the user has rights to the file.

    global $user;
    if ($user->id == $uploaded_user_id) {
        header("Expires: 0"); 
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
        header("Cache-Control: private",false); 
        header('Content-disposition: attachment; filename='. $file;
        header("Content-Transfer-Encoding:  binary"); 
        header("Content-Length: ". filesize(ABSPATH.$upload_dir.$file); 
        readfile($upload_dir.$file);
        exit();
    
    }
    

    now you want to pass a file_id or name to the download script.
    so craft the link like url/download.php?file=$file. You have to call this directly or at the early stages of your plugin or you will get the headers already sent message. The script will check if the user has rights and start to output binary data.

    It should be something like this, hope it helps. Its not the complete but should get you started.