Accountant م Accountant م - 15 days ago 6
Apache Configuration Question

How to protect my php files on the server from being requested

I'm very new to php and web , now I'm learning about oop in php and how to divide my program into classes each in .php file. before now all I know about php program, that I may have these files into my root folder


  1. home.php

  2. about.php

  3. products.php

  4. contact.php



So, whenever the client requests any of that in the browser

http://www.example.com/home.php
http://www.example.com/about.php
http://www.example.com/products.php
http://www.example.com/contact.php


No problem, the files will output the proper page to the client.

Now, I have a problem. I also have files like these in the root folder


  1. class1.php

  2. class2.php

  3. resources/myFunctions.php

  4. resources/otherFunctions.php



how to prevent the user from requesting these files by typing something like this in the browser ?

http://www.example.com/resources/myFunctions.php


The ways that I have been thinking of is by adding this line on top of every file of them
exit;


Or, I know there is something called .htaccess that is an Apache configuration file that effect the way that the Apache works.

What do real life applications do to solve this problem ?

Answer

You would indeed use whatever server side configuration options are available to you.

Depending on how your hosting is set up you could either modify the include path for PHP (http://php.net/manual/en/ini.core.php#ini.include-path) or restricting the various documents/directories to specific hosts/subnets/no access in the Apache site configuration (https://httpd.apache.org/docs/2.4/howto/access.html).

If you are on shared hosting, this level of lock down isn't usually possible, so you are stuck with using the Apache rewrite rules using a combination of a easy to handle file naming convention (ie, classFoo.inc.php and classBar.inc.php), the .htaccess file and using the FilesMatch directive to block access to *.inc.php - http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/

FWIW all else being equal the Apache foundation says it is better/more efficient to do it in server side config vs. using .htaccess IF that option is available to you.

Comments