Working with directories to make a require in PHP

2

I have a page where I generate some information, stored in the Database. This page is within 5 folders: pasta1/pasta2/pasta3/pasta4/pasta5 .

For SELECT to work, I need a require to connect to the bank. This file is in a directory: /conexao/conexao.php .

How can I use require (or another secure command) to perform this query?

    
asked by anonymous 26.11.2015 / 21:27

2 answers

2

If you are using PHP in a webserver, there is certainly a variable that tells the root of the application (or the site) and from that information you should use your paths.

$ _SERVER contains the relevant Webserver information and one of them is DOCUMENT_ROOT.

DOCUMENT_ROOT points to the root of the application. Assuming your application is in the directory x / y / z (here it does not import the operating system), $_SERVER['DOCUMENT_ROOT'] will point to x / y / z correctly no matter what level your PHP script is.

Eventually, for security reasons, you usually put files that should not have direct Webserver access on a path outside that tree. For example: Many Frameworks use a directory structure like this

-./
  -> web
  -> src
  -> test

Where web will be the root of the application. In this case, to access the other directories you should use

ROOT . '/../src';

The PHP manual is the best language documentation I know. Always start your searches over there.

    
26.11.2015 / 21:55
1

An alternative way to another answer would be to simply define the relative path in each file.

Assuming the folder structure is:

+-- ./
    +-- conexao
        +-- conexao.php
    +-- pasta1
        +-- exemplo1.php
            +-- pasta2
                +-- exemplo2.php
                    +-- pasta3
                        +-- exemplo3.php

In the file pasta1/exemplo1.php :

<?php
require '../conexao/conexao.php';

In the file pasta1/pasta2/exemplo2.php :

<?php
require '../../conexao/conexao.php';

In the file pasta1/pasta2/pasta3/exemplo3.php :

<?php
require '../../../conexao/conexao.php';

You can also create an index.php file along with .htaccess and it would access any file.

The file should look something like .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule (.*) index.php/$1 [QSA,L]
</IfModule>

And index.php should look like this:

<?php
require 'conexao/conexao.php';

$pathInfo = isset($_SERVER['PATH_INFO']) $_SERVER['PATH_INFO'] : '';
$pathInfo = ltrim($pathInfo, '/');

if (empty($pathInfo)) {
   echo 'Index normal';
} else if (is_file($pathInfo)) {
   require $pathInfo;
} else {
   header('X-PHP-Response-Code: 404', true, 404);
   echo 'Página não encontrada';
}
    
27.11.2015 / 03:33