Obfuscating file paths
While working on the cloud storage app this week, I was faced with a challenge where I needed the files on the server to be available to users for file previews and downloads, but I did not want to file path to be visible to the users - this way a user could not just save the file path and retain access to the files even after a share expired, for example.
I also needed to prevent users without the proper permissions or file ownership from downloading and viewing the files, for obvious reasons.
There are a few solutions to this challenge - one of them being that the files could be stored outside of the web root, which would prevent direct access to them via the browser. Another possible solution would be to use .htaccess to prevent direct access to specific paths containing the files. Because the files were already being stored inside the document root, I decided to go with the .htaccess method.
The roadblock I faced using the .htaccess method was that I still needed external users to be able to access the files using a pin, so I couldn't easily block all un-authenticated users from accessing the file paths. I'm sure there are some ways of handling authentication using the .htaccess file, but I believed there was another solution so I kept digging.
The solution I eventually settled on was to have file requests be routed through a php file that checks if the user is authenticated with the proper permissions to view the file, and then uses fopen to output the file to the browser.
Now, instead of using the actual server file path for my <img> src, I can do something like this:
<img id="img-preview" src="get_file.php?id=75">
Which will then make a call to my php file with the following code:
if ($IsAuthenticated && is_readable($FilePath)) {
header("Content-Type: ".mime_content_type($FilePath));
$handle = fopen($FilePath,"r");
fpassthru($handle);
fclose($handle);
exit;
} else {
http_response_code(403);
echo "Unauthorized";
exit;
}
This allowed me to use the .htaccess file to block direct access to the actual file paths without affecting external users accessing the files with a pin.
0 Comments