A path is general form of a filename or directory that specified a unique location in a file system. In web programming, a path is used to define links (url) to documents and images or to include a specified library file. There are two standard ways to define a path:
- Absolute Path, is a path that points to the same location on file system regardless of the working directory or combined paths and usually written in reference to root directory.
- Relative Path, is a path that relative to working directory.
In many ways, absolute path is much usefull because it doesn’t need us to redefine the path or link if we change the working directory. For an example, below is a directory hierarchy of a web application that located on a development server that can be accessd via url www.mysite.com, where /var/www/html is it’s web server’s document root and application root directory and ‘/’ is the application root url.
Take a look at index.php in profile directory, to define an url to mypic.jpg in images directory and include lib.php from lib directory:
using absolute path:
<?php include '/var/www/html/lib/lib.php'; $str = '<img src="/images/mypic.jpg">'; ?>
using relative path:
<?php include '../../lib/lib.php'; $str = '<img src="../../images/mypic.jpg">'; ?>
Using absolute path, it wouldn’t be a matter where the working directory is, but it would be a problem if you change the application root directory into another directory other than web server’s document root, for example in /var/www/html/web, so your application would be accesed via www.mysite.com/web. We have to edit manually each file that using absolute path because the root directory will changed to /var/www/html/web so the included file will not work.
To overcome this problem, you have to define a global variable that specified absolute path that generally applied to all directories in your application. The solution is to define two variables which will be used to define root directory for file operations and root url for url operations in a file that would be placed in the root directory .
<?php define('ROOT_DIR', dirname(__FILE__)); define('ROOT_URL', substr($_SERVER['PHP_SELF'], 0, - (strlen($_SERVER['SCRIPT_FILENAME']) - strlen(ROOT_DIR)))); ?>
Save it as init.php and place it in your application root directory.So, from our example above, using the two variables:
<?php include '../../init.php'; include ROOT_DIR . '/lib/lib.php'; $img = '<img src="' . ROOT_URL . '/images/my.pic.jpg">'; ?>
As you can see, it will be applied in any directories regardless where the current working directory or server document root.by