Appearance
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:
Example of using a .htaccess file to block direct access to a file over HTTP but allow PHP script access
apache
<Files myfile.txt>
Require all denied
</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 Require directive:
Example of using a .htaccess file to allow access to a file from a specific IP address
apache
<Files myfile.txt>
Require all denied
Require ip 192.168.0.1
</Files>
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
Note: PHP scripts can still read the file because they access it via the local filesystem path (e.g., file_get_contents(__DIR__ . '/myfile.txt')), not through an HTTP request. Additionally, ensure your Apache configuration allows .htaccess overrides for this directory (e.g., AllowOverride FileInfo or AllowOverride All).
Alternatively, you can also use the mod_rewrite module to block direct access and allow access through a PHP script by adding the following code to your .htaccess file:
Example of using the mod_rewrite module to block direct access and allow access through PHP script
apache
RewriteEngine On
RewriteRule ^myfile\.txt$ - [F,L]This will return a 403 Forbidden error if someone tries to access the file directly, but the PHP script will still be able to access it. To apply this to a directory or multiple files, replace myfile\.txt with a pattern like ^data/.*\.txt$.