I'll be simple and direct. The solution I would give for this would be to structurally divide the application into what is public than it is not.
How?
Creating a folder that contains all the files that will be accessible to the public and pointing Apache to read from that folder. The other files, not being accessible to the client (browser), would be accessible to the script, perfectly serving the dependencies.
Consider the following scenario: I want the user to access my index.php
, contact.php
and about.html
, but he can not access any connection script with database or project classes, which is inside the app
.
I would do so (simulating Linux environment):
projeto/
public/
index.php
contact.php
about.html
css/
default.css
js/
default.js
jQuery.js
app/
classes/
DBConnection.php
Mail.php
Did you notice the above structure? You can simply point VirtualHost from your Apache right into the projeto/public
folder, like this:
<VirtualHost *:80>
#importante apontar para public, não para raiz do projeto
DocumentRoot /var/www/projeto/public
ServerName meusite.com
</VirtualHost>
When you access your site, you will limit the user to access only index.php
, contact.php
and about.html
, as well as the js
and css
/ p>
Note : If you are using OS as Ubuntu, you will probably access VirtualHost in the /etc/apache2/sites-avaliable
folder.
This is how I do it in all my applications.
And you can, by public/index.php
, make an include of a file that is in the app/classes
folder normally. PHP will be able to access, but the browser will not.
For example, by using a structure similar to the one we previously mentioned, we will access the% with% settings stored in a public/index.php
folder.
So:
app/
constantes.php
functions.php
views/
index.tpl
public/
index.php
In the file app
, I have:
define('ROOT_DIR', realpath(__DIR__ . '/../'));
define('VIEWS_DIR', ROOT_DIR . '/views');
In my app/constantes.php
, I do
<?php
include __DIR__ . '/../app/constantes.php';
exit(ROOT_DIR); // '/var/www/projeto
In short: I set public/index.php
as the root of the application.
The mistake many people make is to set the root as the project folder. However, depending on the situation, this can be a bad thing, and forces the programmer to be creating multiple clutter in public
, without any need.
The pattern used above is followed by the Laravel Framework.