Relative paths in scripts and links

Relative paths in scripts and links let you reference files based on the current working directory rather than the full server path. Using relative paths in PHP, ASP and ASP.NET makes your code portable and avoids breaking when the site is moved or the directory structure changes.

Relative path

A relative path assumes the working directory in which the script or file is located. This avoids binding your code to an absolute (full) path that may vary between environments or change over time.

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

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 for ASP and ASP.NET:

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

Function calls

The following function calls can be used instead of typing the full path manually.

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