0
votes

I have a directory named "template". There are some php files that I don't want people have direct access to them, So I wrote this in htaccess :

<Files *.php>
    Order Deny,Allow
    Deny from all
</Files>

Also there is some files that I want people have direct access to them, these files are named as:

switcher.php, switcher1.php, switcher2.php, switcher3.php, switcher4.php, switcher5.php

And located at template/styles/theme/

So I created a new htaccess file in that location and wrote this :

<FilesMatch "^switcher[1-5]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This works good on my localhost, but when I upload the script on a cPanel Shared Host, it didn't work there. Access to all php files denied.

What can I do to fix this problem?

I can't ask hosting to make changes, because this script should installed on at least 30 shared hosts with different configurations!

2
Don't do this. If you don't want to allow access to certain files,then don't put them into the document root at all. can't access what ain't there... And of course, since PHP isn't bound by webserver restrictions for file access, it can still include/require those files all it wants - all you need is an appropriate path in the include/require directives. - Marc B

2 Answers

0
votes

Check for REQUEST_URI in each file:

$file = basename(__FILE__);
if(preg_match("/$file/", $_SERVER['REQUEST_URI'])){
    die('This file cannot be accessed directly!');
}
0
votes

If you have a directory containing PHP includes, that you do not wish to be accessed directly from the browser, there is a way of disabling the directory using Mod_Rewrite.

To enable this, create a .htaccess file following the main instructions and guidance, and include the following text:

## Enable Mod Rewrite, this is only required once in each .htaccess file
RewriteEngine On
RewriteBase /
## Test for access to includes directory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC]
## Test that file requested has php extension
RewriteCond %{REQUEST_FILENAME} ^.+\.php$
## Forbid Access
RewriteRule .* - [F,NS,L]

Where /includes/ is your includes directory.

Note: I strongly recommend to store your files, that you don't want to be accessed directly by the user, in a separate directory / folder. Don't worry, you can access these files using include method.