X Pahadi
X Pahadi

Reputation: 7443

PHP require_once Absolute Path vs Relative Path (Not Working)

Well, I am still very confused how this is possible. Look at the following two lines of code:

Code on Connection.php in class folder:

require_once '../config/constants.php';

require_once dirname(__DIR__).'/config/constants.php';

The second works totally fine, but the first throws the error of:

No such file in ...... on line... in Connection.php

It's getting on my nerves, what is the difference between the two? In my years of programming, I never encountered such problem? Am I missing some points?

If you have any documentation you would like to offer then provide. I would like to have a good foundation of knowledge than just solving problem.

Directory Structure:

enter image description here

Upvotes: 2

Views: 2256

Answers (1)

Narf
Narf

Reputation: 14752

../ denotes the parent directory, compared to the one you're currently in. Therefore, your first line says "go one directory up and look for config/constants.php in there". What you'd want to use with a relative path here is ./ (note the single dot), which denotes your current directory.

This has little to do with programming in specific, it's more of a file-system thing.

You can use this as a reference:

  • leading / (no dots, just a slash) means an absolute path
  • leading ./ (single dot) means the current directory
  • leading ../ (two dots) means one directory up
  • no leading dots or slashes is the same thing as with the single dot - relative to the current directory.

Update (to account for edited question):

What has something to do with programming and PHP in particular is that what is considered the "current" directory is usually the one where you initially executed the script from. Under a CLI environment, that may vary, but if you're accessing the script via the web that is the location of the PHP file which you have directly accessed. E.g. if you're pointing your browser to example.com/test.php, then wherever 'test.php' is located is the directory you're currently in.

That can be changed by chdir() of course.

Upvotes: 6

Related Questions