I’m going to be simple and straightforward. The solution I would give for this would be to structurally divide in the application what is public of what is not.
Like?
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, which are not 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 mine index.php
, contact.php
and about.html
, however it cannot access any connection script with database or project classes, which is inside the folder 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
Notice the above structure? You can simply point your Apache’s Virtualhost directly to the folder projeto/public
, thus:
<VirtualHost *:80>
#importante apontar para public, não para raiz do projeto
DocumentRoot /var/www/projeto/public
ServerName meusite.com
</VirtualHost>
With this, when you access your website, you will limit the user to access only index.php
, contact.php
and about.html
, as well as the folders js
and css
, with their respective contents.
Observing: If you are using OS as Ubuntu, you will probably access Virtualhost in the folder /etc/apache2/sites-avaliable
.
That’s how I do it in all my apps.
And you can, by public/index.php
, make a include of a file that is in the folder app/classes
normally. PHP will be able to access, but not the browser.
For example, using a structure similar to the one mentioned above, we will access through public/index.php
settings stored in a folder app
.
Thus:
app/
constantes.php
functions.php
views/
index.tpl
public/
index.php
In the archive app/constantes.php
, I have:
define('ROOT_DIR', realpath(__DIR__ . '/../'));
define('VIEWS_DIR', ROOT_DIR . '/views');
In my public/index.php
, i do
<?php
include __DIR__ . '/../app/constantes.php';
exit(ROOT_DIR); // '/var/www/projeto
To summarize: Defini public
as the root of the application.
The mistake many people make is to define the root as the project folder. However, depending on the situation, this can be bad, and forces the programmer to keep creating various messes in the .htaccess
, needlessly.
The pattern used above is followed by the Laravel Framework.
You use apache?
– Wallace Maxters
Yes! Apache server!
– Jose Henrique
Which operating system do you use? Windows? Linux?
– Wallace Maxters
Windows with wampserver
– Jose Henrique