如何防止用户在服务器上打开文件?

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

You should not leave them in a publicly accessible location on your web server.

You can restrict access to individual files or groups of files in your .htaccess file. This thread has several ways to do it.

There are several different ways to do this, via sessions, or user permissions', or based on whether or not the user is logged in for example..

Reviewing something like this might help you out to get started

https://www.wmtips.com/php/simple-ways-restrict-access-webpages-using.htm

Set the permission for the file to 0 0 0. That way You can only open the file via Admin Panel.

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");

Create a .htaccess file there where your index.php is located and write this

<Files *.txt>
Deny from all
</Files>