0

New to PHP so trying to work out how relative and absolute paths work with require.

My structure looks like:

/index.php
/inc/db_functions.php
/inc/config.php
/login/login.php

db_functions.php includes config.php using require_once 'inc/config.php';

index.php includes db_functions.php using require_once 'inc/db_functions.php';

If the user is not logged in then the browser redirects to login.php. Originally login.php was in the root folder and used the same require once as index.php. It worked perfectly.

Now it is in its own subfolder. I changed the require_once to use require_once('../inc/db_connect.php');

The code worked until it got to the require_once line in db_connect.php and then failed.

I changed the require once in login.php to be: require_once(__DIR__.'/../inc/db_connect.php');

Again it failed when it got to the require_once in db_connect.php

I changed the require_once in db_connect to be an absolute path. Again it failed.

Is there any way to deal with this as it seems that the include paths for an included file are changed by the location of the calling file ( which I guess makes sense) but how to make it more robust.

brombeer
  • 8,716
  • 5
  • 21
  • 27
Flugan
  • 33
  • 3
  • 1
    Please edit your question so it does contain the source code of your files and write the error messages you get. However, the magic constants `__DIR__` should do the trick. – Progman Oct 15 '17 at 09:35
  • Hi. I'll try to upload the code but it is quite a few lines long so I'll trim it first. Also I don;t get an error message. The debugging under netbeans just stops on that line and doesnt proceed. – Flugan Oct 18 '17 at 07:54
  • You might need to check https://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php to see how to get error messages from your php script. – Progman Oct 18 '17 at 17:30

1 Answers1

0

db_functions.php must include config.php using require_once 'config.php'; because they are in same folder.

In general, best would be to use full paths.

wast
  • 878
  • 9
  • 27