I have my hosting in a shared hosting (I don't think that's relevant). I want to perform some actions inside a php script, and those actions include reading from a file. I would like that file not to be accesible by anyone, only by the php script (otherwise anyone would be able to get that file without permission just by accessing the link). How can I do that?
- Set a file as private / non accessible through its URL
- Setup a php script that can actually read this file
Thanks.
CodePudding user response:
You can easily forbid access to a folder by adding a .htaccess with this code :
deny from all
Then you can still access it through PHP with fopen()
or file_get_contents()
CodePudding user response:
Method: .htaccess file
As mentioned in https://stackoverflow.com/a/70365577/7335057, you could use a .htaccess file, as long as you are using an apache or compatible webserver.
Method: Unique URLs
It is also perfectly reasonable to have long random links.
https://example.com/usercontent/326a98f7a6c61fb3e37c310c414ca23b16948b4a/test.jpg
You need to make sure the links are not able to be found using brute force as well as only link to files the current user is allowed to see.
The 326a98f7a6c61fb3e37c310c414ca23b16948b4a
part of the URL has to be unique for every user. it can not be the userId hashed or something like that.
Here is an example of how to generate a highly unique but random string for your URL:
$partLength = 10;
$fix = "your-app-node-1";
$time = microtime(true);
$random = random_int(1000000, 9999999);
$urlPart = substr(sha1($fix), -$partLength)."-";
$urlPart .= substr(sha1($time), -$partLength)."-";
$urlPart .= substr(sha1($random), -$partLength);
The fix part is mainly for when you use multiple servers, so ids don't colide.
Method: Files outside the root folder
Not all hosters of shared webspaces allow that, but if yours does, put the files in a folder above the root directory to make them not accessible through a web request. Be aware of path traversal attacks though.
Files outside the root dir are usually still accessible using PHP.