Question

So I had this trouble with a PHP code that I solved, but I don't really know how it works.

I tried to add this to every single file

<?php include '/nav.php'; ?>

So I can only have one file to edit the navbar instead of the whole php files.

The problem came up when I added that code to the files of another folder (ie. /general/vision.php) and I got an error (file not found). I though it was because I only hav the 'nav.php' file on the root of the site.

So, just for fun, I changed the sentence of the /general/vision.php file to

<?php include '../nav.php'; ?>

And it worked. I didn't changed the nav.php from the root, and it worked.

I'm glad it did, but I don't know why. How does that /../ works? Is that listed on the PHP documentation?

Was it helpful?

Solution

.. is OS nomenclature for "up a directory." It's nothing PHP specific.

Take a look at the concept of Relative paths.. might shed some light. Relative paths vs Absolute paths.

OTHER TIPS

.. refers to the parent directory. This is pretty standard for all operating systems.

PHP is a server side scripting language, which means the root directory / is not the document root of your website, but the root of your filesystem on the server.

By beginning your path with / you are specifying an absolute path to the file, starting from the root. You can build a path relative from the current directory by using for example .. to ascend one level.

You can also build an absolute path using the __DIR__ constant in PHP, which always contains the full absolute path to the directory which contains the current PHP file, for example include __DIR__ . '/../nav.php';.

While you solved your problem by having .. (parent directory) in your include path, it is better to include the php file like this:

 include $_SERVER['DOCUMENT_ROOT']."/nav.php";

Then you can keep your PHP files anywhere in DOCUMENT_ROOT and will still be able to include this nav.php file.

PS: Its a good practice to keep common include files a level above DOCUMENT_ROOT so that these files cannot be directly accessed by browsers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top