相对路径的计算

Computation of relative path

本文关键字:计算 路径 相对      更新时间:2024-05-07

我在理解相对路径概念时遇到了困难,我看到了一部分代码被写成

../../abc/file/images/picutre/down.gif

如何计算相对路径

相对路径是相对于工作目录的路径。换句话说,查找文件的起点是从工作目录。

相对路径中的"../"表示向上一个目录。

假设您引用的是index.html页面中的相对路径../../abc/file/images/picutre/down.gif,其结构如下:

http://someexampleurl.com/dir1/dir2/index.html

index.html中工作时,您的工作目录是/dir2,因此考虑到您要升级两个级别,浏览器希望文件位于:

 http://someexampleurl.com/abc/file/images/picutre/down.gif

如何计算相对路径

基本上,相对路径是从您所在的目录到需要包含的文件的"映射"。因此,相对路径是根据您要去的地方来计算的。

例如,您有一个结构

/ (document root)
|--home.php
|--t.php
|--common
      |--header.php
      |--footer.php
|--support
      |--index1.php
|--privacy
|     |--index2.php

home.php,您需要包括headerfooter。因此,您的家庭代码将看起来像

<?php
include("common/header.php"); // go one folder down (common) and grab the file header.php
include("common/footer.php"); // go one folder down (common) and grab the file footer.php

现在假设您在index1.php中提供支持,并且您需要header.phpfooter.php。你的代码看起来像

<?php
include("../common/header.php"); // go one folder up (common) and grab the file header.php
include("../common/footer.php"); // go one folder up (common) and grab the file footer.php

将文件夹中的文件夹视为级别(级别1、级别2等)

注意:小心相对路径——这是一种痛苦。

它说从当前位置返回两级(父目录)"../../"。

因此,如果我们在https://example.com/my/path/here上,并且它加载了一个文件../../abc/file/images/picutre/down.gif,那么由于../https://example.com/my的2个目录,我们将转到2个目录。然后我们将转到/abc/file/images/picutre/down.gif。因此,最终目的地将是https://example.com/my/abc/file/images/picutre/down.gif

  1. down.gif存在于同一目录中
  2. /从根目录启动
  3. ../从当前目录返回一个目录
  4. ../../从当前目录返回两个目录