1

I have a file index.php in root directory:

<?php
require_once "./include/common.php";
?>

and file common.php in include folder:

<?php
require_once "globalConfig.php";
?>

file globalConfig in the same folder with common.php. The tree folder as:

xxx/index.php

xxx/include/common.php

xxx/include/globalConfig.php

index.php run normally. But if I change file common.php as:

<?php
require_once "./globalConfig.php";
?>

PHP show a warning that it cannot find the globalConfig.php file. What is the difference? I think int the case with "./", the most outside including file (index.php) will find the globalConfig.php in its current directory.

coolkid
  • 543
  • 8
  • 21
  • 1
    See also http://stackoverflow.com/questions/1395909/php-include-all-paths-get-messed-up, http://stackoverflow.com/questions/3429780/include-and-path-problem, and lots of other questions from a search for "php include path" :) – Bobby Jack Sep 07 '10 at 10:43

3 Answers3

3

In your index.php add

define('BASE_PATH',str_replace('\\','/',dirname(__FILE__)));

And then within common.php include like so.

require_once BASE_PATH . '/includes/globalConfig.php';

This will find the exact path and standerize the slashes, then whenever you use BASE_PATH alsways include from the root of your htdocs, ie index.php.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
  • As the str_replace converts backslashes to slashes its windows and linux compat, I use in every project. Your Welcome. – RobertPitt Sep 07 '10 at 10:48
2

The path is relative to the current working directory; in a web context (php-cgi), this is the directory where the initially invoked script (the one that gets started directly instead of through on include) resides. An easy workaround:

require_once dirname(__FILE__) . '/foobar.inc.php';
tdammers
  • 20,353
  • 1
  • 39
  • 56
1

I believe that the path (i.e. "./") is relative to the BASE script, not the file it's contained within. For this reason, I usually use absolute paths when including scripts.

Bobby Jack
  • 15,689
  • 15
  • 65
  • 97