The Difference Between Relative and Absolute Paths
Often source of errors, pages not found, missing images or not applied styles, the format of writing the links is very important. And yet, it does not necessarily guard to the way we do point these last to different target files. Following the convention of writing used, many problems can occur. Indeed, two types of writings will co-exist, each with their own uniqueness:
- the initial relative (without slash) path
- the path absolute (slash in the path prefix)
On the web
Relative path
dossier/page.html
The target (page.html) will be sought by the browser from the html page or the stylesheet it interprets, in the subdirectory "folder".
./dossier/page.html
./
: means that the page is looked for from the current directory.../dossier/page.html
../
: means that the page is looked for from the parent directory (it goes up a level).
It is quite possible to trace several directories. This to combine the
../
and so to go up two levels, it will be possible to write ../../dossier/page.html
.Absolute path
/dossier/page.html
The initial slash says that one refers more to the location but we go back directly to the root to then specify the full path.
In many cases, the absolute path is the convention of writing the safer, but also the less flexible if the tree is subject to change. The target page will be sought by the browser from the root of the site.
In our example, the file page.html will be sought directly from the root of the domain:
http://www.mondomaine.fr/dossier/page.html
.Language (PHP, Ruby, Python...) server-side
The relative path
dossier/page.php
./dossier/page.php
../dossier/page.php
The target (page.php) will be sought from the executed file. Attention: If you use the convention of writing to a file using the
include()
function, be aware that relative path that starts not to the file itself, but of the file in which the content is placed: it comes from the the file that is executed by the server.Absolute path
/dossier/page.php
The target will be sought from the root of the file system that is represented by the initial slash:
/
.
(For example on Windows:
include('/inc/menu.php');
is equivalent to C:>inc\menu.php
and not http://www.domaine.fr/inc/menu.php
which is inside only a "virtual" view of the directory that hosts the site, and who can be placed anywhere in the tree view of the storage system. On Linux, this would be traced back to the first level of the tree of the mount point.
To get the root of the web server, use the PHP variable
$_SERVER['DOCUMENT_ROOT']
as a prefix.
Post a Comment