Search code examples
php.htaccess

how to prevent url force access to files


After uploading a file to the server, I store the file path in the database.

http://localhost/ramseyer/apps/uploads/-d10ddbe8164659168192848723610514347.docx

Since the platform I am building has user access levels, I realize that even if the user is not logged in with authorization, a user can still access the file only if they somehow get to know the URL.

I've read many articles about path traversal but did not find answers.

Is there a way to forbid a user who tries to enter the file URL in the address bar just to access the file? Just as you forbid a user from accessing directories with htaccess ?


Solution

  • You can use RewriteRule like this:

    RewriteRule ^(.*)\.(pdf|docx)$ download.php?file=$1&ext=$2
    

    Please check the documentation here: https://httpd.apache.org/docs/current/mod/mod_rewrite.html

    In the download file you should check the user credentials first and then output the file contents + headers.

    // check credentials...
    
    $filename = $_GET['file'] . '.' . $_GET['ext'];
    $filename_url = $path_to_file . '/' . $filename;
    
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header("Content-Type: text/" . $_GET['ext']);
    header("Content-Length: " . filesize($filename_url));
    
    echo file_get_contents($filename_url);