views:

300

answers:

2

I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up. I decided to go with the set_include_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.

Is there a guide somewhere that details path referencing for PHP?

+1  A: 

it's probably easier to just use an absolute path to reference:

set_include_path('/path/to/files');

this way you have a reference point for all your future includes. includes are handled relative to the point they were called, which can cause a bit of confusion in certain scenarios.

as an example, given a sample folder structure (/home/files):

index.php
test/
  test.php
test2/
  test2.php

// /home/files/index.php
include('test/test.php');

// /home/files/test/test.php
include('../test2/test2.php');

if you call index.php, it will try to include the following files:

/home/files/test/test.php // expected
/home/test2/test2.php // maybe not expected

which may not be what you expect. calling test.php will call /home/files/test2/test.php as expected.

the conclusion being, the includes will be relative to the original calling point. to clarify, this affects set_include_path() if it is relative as well. consider the following (using the same directory structure):

<?php
// location: /home/files/index.php
   set_include_path('../'); // our include path is now /home/

   include('files/test/test.php'); // try to include /home/files/test/test.php
   include('test2/test2.php'); // try to include /home/test2/test2.php
   include('../test3.php'); // try to include /test3.php
?>
Owen
where exactly does that start? is it relative to apache or is it set in php.ini or is it the php directory itself?
E3
by default the include is relative to the calling location (ie the directory your script which calls include is in)
Owen
in regards to set_include_path('../'); - if i wanted to set the include path to 2 directories up how would i put it?
E3
sorry never mind, figured out that each . represents one step up
E3
+2  A: 

I tend to use dirname to get the current path and then use this as a base to calculate all future path names.

For example,

$base = dirname( __FILE__ ); # Path to directory containing this file
include( "{$base}/includes/Common.php" ); # Kick off some magic
Rob
You got my +1, but please avoid "{$var}". Why not `$base . '/includes/Common.php'`?
eyelidlessness
Excuse the fact that backticks didn't properly encode here.
eyelidlessness
I prefer setting the include-path and not using variables in each include/require statement.
troelskn
eyelidnessless: I find it a touch easier to read. There's no difference between the two.
Rob