Mevia
Mevia

Reputation: 1564

PHP Relative paths for require file

I've been going over those two topics:

and couldn't make my script to work, none of presented methods are working or maybe I'm doing something wrong.

Anyway this is where my problem occurred:

Root/                                   //this is root location for server
APP/                                    //this is root location for script
Root/APP/core/init.php                  //this is where I include classes and functions from
Root/APP/classes/some_class.php         //this is where all classes are
Root/APP/functions/some_function.php    //this is where all functions are

and so obviously I need to include init.php everywhere so I did in every file like this:

require_once 'core/init.php';

it was working until I have decided to create a location for admin files like this:

Root/APP/Admin/some_admin_file.php

and when I included init this way:

require_once '../core/init.php';

script failed to open functions, no such file in APP/Core/ folder so I used DIR method presented in topic above and than even weirder thing happened, error:

no such file in APP/Core/classes/Admin/

What is that? :D I'm lost with this, could someone help a bit ;)

Upvotes: 1

Views: 180

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173662

Include paths are relative to the current working directory, which can be inspected using getcwd(); this can be a source of many issues when your project becomes bigger.

To make include paths more stable, you should use the __DIR__ and __FILE__ magic constants; for instance, in your particular case:

require_once dirname(__DIR__) . '/core/init.php';

The dirname(__DIR__) expression is effectively the parent directory of the script that's currently being run.

Btw, __DIR__ could also be written as dirname(__FILE__).

Upvotes: 2

Related Questions