簡體   English   中英

PHP頁面的公共URL

[英]Public URL of a PHP page

訪問時

www.example.com/test1/test2/index.php

(該文件是服務器上的/var/www/website1/test1/test2/index.php

我們得到:

<base href="<?php echo __DIR__; ?>">  
// bad:  <base href="/var/www/website1/test1/test2/">

<base href="<?php echo dirname($_SERVER['REQUEST_URI']); ?>">
// bad: <base href="/test1/test2">
//      a <base href> dir must end with a / (or \ on Windows)

<base href="<?php echo rtrim(dirname(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH)), '/') . '/'; ?>">  
// good:  <base href="/test1/test2/">

最后一個解決方案有效(*),但我發現它有點臟/ hack。 有沒有更干凈的解決方案來設置<base href="...">當前PHP文件的目錄?

(*)實際上,最后一種解決方案不適用於Windows服務器,因為添加'/'會破壞<base href> (應為'\\')。

dirname($_SERVER['SCRIPT_NAME']);

應該管用。 否則,請執行以下操作:

在PHP <5.3中:

substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));

或PHP> = 5.3:

substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));

根據您的評論進行更新:

如果腳本在Windows上運行,請使用適用於linux的解決方案,相應地修改路徑。

檢測服務器操作系統:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

要么

if (DIRECTORY_SEPARATOR == '/') {
    // linux
}

if (DIRECTORY_SEPARATOR == '\\') {
    // windows
}

暫無
暫無

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

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