user9026111
user9026111

Reputation:

include strange behaviour with relative path

In my php project I try to include another file. However, I find it very confusing how the include statement works.

e.g. I include the file HelperFile.php in index.php. Both files are in the same directory.

This works: include 'HelperFile.php' but this doesn't include '/HelpferFile.php' & include './HelpferFile.php'

The warning I receive:

PHP Warning include(/HelperFile.php): failed to open stream

Out of curiosity I created a folder and moved my file HelperFile.php into it and nothing changed. Everytime I tried to use the relative path with ./, ../ or /I received a warning.

Can someone explain me what's going on. I'm still learning and can'f figure out what's happening right now.

Upvotes: 0

Views: 224

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34924

PHP Doc says

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

If you use . or .. will ignored for relative path Also use ../ for parent directory.

Upvotes: 0

Simon R
Simon R

Reputation: 3772

PHP isn't so great with relative paths, it generally prefers absolute paths. The easiest way around this is to use the DIR magic constant which returns the current directory of the file you're currently in.

So, for instance, you can do include(__DIR__ . '/HelperFile.php'); which would be in the current directory.

However say you had a file in a folder up you can do
include(__DIR__ . '/../MyOtherFile.php');

Upvotes: 1

Related Questions