簡體   English   中英

PHP獲取從父級到包含文件的相對路徑

[英]PHP Get Relative Path from Parent to Included File

我有這樣的目錄結構:

www/
  index.php
  my-library/
    my-library.php
    assets/
      my-library.css
      images/
        loading.gif

我需要my-library.php將樣式表注入index.php 為此,我需要獲取從index.phpmy-library/的相對路徑-在這種特殊情況下,它只是"my-library"

my-library.php ,我是否可以獲取此相對路徑?

還是必須index.php用以下內容提供它?

<?php
require "my-library/my-library.php";
$mlib->linkroot='my-library';
?>

為了澄清起見,下面我提供了我要執行的操作的更詳細表示:

index.php文件:

<?php require "my-library/my-library.php"; ?>
<!doctype html>
<head>
  <title>Testing My Library</title>
  <?php $mlib->injectAssets(); ?>
</head>
<body>..</body>

我-library.php:

<?php
class MyLibrary(){
  public $rootpath;
  public $linkroot;
  function __construct(){
    $this->rootpath= __DIR__; // absolute path to my library's root directory (for serverside use)
    $this->linkroot = "???"; // relative path to my library's root from index.php (for clientside use, like linking in stylesheets)
  }
  function injectAssets(){
    $csslink = $this->linkroot.'/assets/my-library.css';
    echo '<link href="'.$csslink.'" rel="stylesheet" />';
  }
}
$mlib = new MyLibrary();
?>

我感興趣的那一行是$this->linkroot = "???";

我實際上是在嘗試獲取用於包含/獲取當前腳本的字符串。

我知道了! 我只需要制造一台Rube Goldberg機器即可!

謝謝PHP

$linkroot = ascertainLinkroot();

function ascertainLinkroot(){
  return makeRelativePath(
    getTopScriptPath(),
    __DIR__
  );
}

function getTopScriptPath(){
  $backtrace = debug_backtrace(
    defined( "DEBUG_BACKTRACE_IGNORE_ARGS")
      ?DEBUG_BACKTRACE_IGNORE_ARGS
      :FALSE );
  $top_frame = array_pop($backtrace);
  $top_script_path = $top_frame['file'];
  return $top_script_path;
}

function makeRelativePath($from,$to){
  // Compatibility
  $from = is_dir($from) ?rtrim($from,'\/').'/' :$from;
  $to   = is_dir($to)   ?rtrim($to,'\/').'/'   :$to;
  $from = str_replace('\\','/',$from);
  $to   = str_replace('\\','/',$to);
  //----------------------------
  $from = explode('/',$from);
  $to   = explode('/',$to);
  $path = $to;
  foreach($from as $depth => $dir) {
    if ($dir === $to[$depth]) { // find first non-matching dir
      array_shift($path); // ignore it
    } else {
      $remaining = count($from)-$depth; // get number of remaining dirs to $from
      if ($remaining>1){
        // add traversals up to first matching dir
        $padLength = -(count($path)+$remaining-1);
        $path = array_pad($path, $padLength, '..');
        break;
      } else {
        $path[0] = './'.$path[0];
      }
    }
  }
  return rtrim(implode('/', $path),'\/');
}

因此,基本上,我使用makeRelativePath函數來計算從頂部腳本的絕對路徑到當前腳本的絕對目錄路徑( __DIR__ )的相對路徑。

我意識到我實際上是在從頂部腳本 (而不只是父腳本)中查找庫的相對路徑,因為頂部腳本是需要相對於客戶端資產進行引用的腳本。

自然,PHP不僅您提供了頂級腳本的絕對路徑。 在某些環境中,頂級腳本的路徑可以作為$ _SERVER變量使用,但是環境獨立性對我來說很重要,因此我必須找到一種方法。

getTopScriptPath是我的解決方案,因為它使用debug_backtrace進行查找(令人毛骨悚然,據我所知),但這是唯一與環境無關的方式(據我所知)。

仍然希望有一個更優雅的解決方案,但對此解決方案感到滿意。

我相信這就是您要尋找的:

$this->linkroot = basename(pathinfo($_SERVER['REQUEST_URI'], PATHINFO_DIRNAME));

您可以刪除basename()以獲得完整路徑。 基本上,您可以運行以下代碼:

echo '<pre>';
var_dump($_SERVER);
echo '</pre>';

如果您要查找的路徑沒有某種形狀或形式,那么它根本就不可用,您別無選擇,只能對其進行硬編碼,或者至少對其進行硬編碼。

您是否嘗試過從根開始進行相對鏈接? 如果沒有,如果我了解您的文件夾結構,則可以嘗試這樣的操作。

<link href="/my-library/assets/my-library.css" rel="stylesheet" type="text/css" />

您網站內任何頁面中的此類鏈接將在網站結構中上移或下移相同的樣式表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM