Understanding paths in PHP

Ever wondered how to properly include files? Here's your chance

There are two ways of including files in PHP: relative and absolute. Example code below shows how to properly include Thumbnailer class. PHP offers two including functions: include and require. The former should only be used for non important files like template files, the latter for libraries, classes etc.

<?php
// for example this is index.php file
// and Thumbnailer class is located in the same folder

// absolute inclusion
// dirname(__FILE__) will output the full path
// to the current file
// correct way
require dirname(__FILE__).'/Thumbnailer.php';

// if the Thumbnailer is located in the parent directory
// named 'classes'
require dirname(__FILE__).'/../classes/Thumbnailer.php';

// check this out
echo "File being executed: "__FILE__ "<br/>";
echo 
"Absolute directory of file being executed: "dirname(__FILE__) . "<br/>";

// relative inclusion
// you should not use it
require 'Thumbnailer.php';

?>

Both examples will give a same result, but the latter can, on some other servers, cause problems if the INCLUDE_PATH constant is not set to . (dot). Usually it is set to .;.. which means PHP will always look for included files in the same directory and the parent directory.