Relative paths in scripts and links

When writing a script, you should avoid specifying the absolute (full) paths. This is to avoid to unduly bind the function to the path which may or may vary or change. A better solution is to use the relative path which means that one assumes the working directory where the script or the file is located.

Relative path

If you want to reach a file called file.txt located in the directory directory/ the relative path is directory/file.txt.

In order to reach the file file2.txt located in the directory directory2/ from directory/ the relative path is ../directory2/file2.txt.

The example below shows how to include a text file with PHP:

<?php include("directory/file.txt"); ?>
<?php include("../directory2/file2.txt"); ?>

The same example as above but for ASP and ASP.NET:

<!--#include file="directory\file.txt"-->
<!--#include file="..\directory2\file2.txt"-->

Function calls

Function calls that can be used instead of typing the full path.

Absolute path with ASP and ASP.NET:

Server.MapPath("directory\file.txt")

Absolute path with PHP:

dirname(__FILE__) . "/directory/file.txt"
Was this article helpful?

Related Articles