Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent users from opening a file on the server?

This question may sound dumb, well indeed it is dumb.
I have some files on my server:
index.html, file.txt
How do i prevent users from opening file.txt with entering this as their url: website.domain/file.txt? Is this possible easily, or do i have to make some special folders or other dark magic? Thanks


1 Answers

The simple solution is to store the file outside the public folder. (In your case public = htdocs)

For example:

├── protected.txt
├── public
│   ├── index.html
│   ├── exec.php

And then in your exec.php you can access the file with:

echo file_get_contents(__DIR__ . "/../protected.txt");

(Method #2)

Since you mentioned in the comments that you are using XAMPP that means you are running your server on Apache, I can show you a different approach using htaccess.

├── public
│   ├── index.html
│   ├── exec.php
│   ├── protected
│   │   ├── .htaccess
│   │   ├── protected.txt

And then in your .htaccess you write:

deny from all

That will make every file inside protected folder unaccessible via HTTP.

And your exec.php file will look like this:

echo file_get_contents(__DIR__ . "/protected/protected.txt");
like image 55
HTMHell Avatar answered Dec 03 '25 22:12

HTMHell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!