Block direct access to a file over http but allow php script access

One way to block direct access to a file over HTTP but allow PHP script access is to use a .htaccess file in the same directory as the file. The .htaccess file can contain the following code:

<Files myfile.txt>
Order Allow,Deny
Deny from all
</Files>

This will block all direct access to the file "myfile.txt" from any IP address. If you want to allow access to the file from a specific IP address, you can use the "Allow from" directive:

<Files myfile.txt>
Order Allow,Deny
Allow from 192.168.0.1
Deny from all
</Files>

Watch a course Learn object oriented PHP

Alternatively, you can also use the mod_rewrite module to block direct access and allow access through PHP script by adding the following code to your .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^myfile\.txt$ - [R=404,L]

This will return a 404 error if someone tries to access the file directly, but the PHP script will be able to access it.