Error with the file paths in PHP when doing require ()

3

I am working with PHP and a problem has arisen that I have been looking for and I have not been able to solve. The problem comes when in a class I try to require another class in this way:

require 'DAO/usuario.php';

But when it comes to these lines it gives an error:

require '../../compra.php'

The error is as follows:

require (../../compra.php): failed to open stream: No such file or directory

But the route exists, and it is. Someone knows why he gives this error with that route and knows how to fix it. Thanks.

    
asked by RodriKing 02.03.2017 в 09:52
source

1 answer

4

You are using a relative path and, depending on the string of requires e includes that you have defined, what is two directories above DAO/usuario.php is not two directories above the initial script.

Let's say you have it that way

- index.php 
  - otro directorio
    - otro_script.php
      - DAO
        - usuario.php

It would be understood that compra.php is in the same directory as index.php , but it turns out that usuario.php is running at compile time along with index.php , so you're calling a file two directories above index.php and that clearly does not exist.

What I always recommend is to keep a single point of entry to the application (index.php) where a constant that sets the root directory is defined:

index.php

<?php

define('HOMEDIR',__DIR__);

require(HOMEDIR.'/OtroDirectorio/DAO/usuario.php');

And in user.php

<?php

require(HOMEDIR.'/compra.php');

And the real good practice here is to use Composer and autoloading , so that the namespace of each class defines its location deterministically in the file tree, but sometimes it does not need to be complicated if you are experimenting or doing a proof of concept.

    
answered by 02.03.2017 / 13:39
source