relative v. absolute paths

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have a php file that when I include it from my homepage, I specify:

   require_once './library/php/head.php';

head.php itself includes another php file in the middle of its text:

   require_once './library/php/javascript.php';

That works and is all well and good.

However, if I then try to use head.php from other php files in
subdirectories, then the path to javascript.php is no longer valid and

If I were to specify an absolute path to javascript.php, it should
work from any other location.

I'm a beginner at PHP so I have always abided by the idea that all php
files should be included with a relative path.  Is this always true?

If so, is there a better way to do this?   Thanks a bunch.

Re: relative v. absolute paths

El 01/04/2011 7:28, Evolution escribió/wrote:
Quoted text here. Click to load it

Relative paths are relative to the location of the _main_ script(*). You
can make a simple test to prove it. Add this to your head.php file:

<?php echo realpath('./') . PHP_EOL; ?>

Then require head.php from files at:
- /test.php
- /library/test.php
- /library/php/test.php

The easier way to understand it is to think of include/require as a sort
of copy & paste: the main script incorporates to itself the source code
of the included files and it runs exactly the same as it was physically
on the main file.

(*) Unless you chdir() to another directory.

Quoted text here. Click to load it

Some people provide no path at all and rely on the include_path php.ini
directive. I particularly find it easier to just provide full paths at
all times. You can use $_SERVER['DOCUMENT_ROOT'] if your host provides
it and it's reliable or build a DOC_ROOT constant:

require_once DOC_ROOT . 'library/php/javascript.php';

-- - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
-- Mi web de humor satinado:

Re: relative v. absolute paths

On Apr 1, 12:38=A0am, "=C1lvaro G. Vicario"
Quoted text here. Click to load it

Thanks, Alvaro, that helped a lot.  This is how I wrote it and
everything now works again:

      $html_title = $_SESSION['html_title'];
      print "<title>$html_title</title>";
      $docRoot = getenv("DOCUMENT_ROOT");
      require_once $docRoot . "/library/php/javascript.php";

It's really nice to have the primary javascript all in once place so I
don't have to have javascript code on every page that is not even used
for anything but one page.

Before I used the above, I tried to assign the result of realpath to a
variable but wasn't able to succeed.  While PHP is mostly just like
every other programming language, it sure has its peculiarities.  :)

Thanks again.

Site Timeline