【问题标题】:whats a good way of always having the correct doc root string?始终拥有正确的文档根字符串的好方法是什么?
【发布时间】:2010-02-08 12:57:52
【问题描述】:

如果我有这样的菜单

<a href="index.php">home</a>
<a href="aboutus.php">about us</a>
<a href="contact.php">contact us</a>

在一个名为 menu.php 的文件中

并且这个 menu.php 文件被包含在整个应用程序的页面中。但是如果我创建一个新文件夹并将其命名为投资组合,并且在此文件夹中有一个名为 example1.php 的文件,并且 menu.php 包含在此文件中,该怎么办。主页、关于我们和联系我们的链接将不再有效,因为它们指向根。所以我创建了这个函数

function getRoot() {

    $self = $_SERVER['PHP_SELF'];
    $protocol = $_SERVER['https'] == 'on' ? 'https:/' : 'http:/';
    $docroot_before = explode("/", $self);
    array_pop($docroot_before);
    $docroot_after = implode("/", $docroot_before);
    $host = $_SERVER['HTTP_HOST'];

    return  $protocol.$host.$docroot_after."/";
}

菜单现在看起来像这样

<a href="<?=getRoot();?>index.php">home</a>
<a href="<?=getRoot();?>aboutus.php">about us</a>
<a href="<?=getRoot();?>contact.php">contact us</a>

the link should come out as  http://localhost/domain/aboutus.php (for example)
but it comes out as http://localhost:/domain/portfolio/aboutus.php (and this is wrong).

无论 menu.php 包含在何处,始终获得正确文档根目录的最佳方法是什么?

【问题讨论】:

    标签: php


    【解决方案1】:

    如果 URL 以单斜杠 (/) 开头,那么它将链接到根文件夹。只要您的页面位于根文件夹中(即http://www.example.com 而不是http://www.example.com/foo),那么以下内容将起作用:

    <a href="/index.php">home</a>
    <a href="/aboutus.php">about us</a>
    <a href="/contact.php">contact us</a>
    

    如果您在子域中,则将/ 更改为/subdomain/

    【讨论】:

    • 是的,我在想,但是如果它的特定文件不在根目录中,而不必去更改菜单文件中的一些文件链接信息,php 怎么能检测到它的位置呢?次?
    【解决方案2】:

    我在自制框架中使用以下内容...将其放入应用程序根文件夹中的文件中并简单地包含它。

    define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');
    
    $tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));
    $tempPath2 = explode('/', substr(ABSPATH, 0, -1));
    $tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));
    
    for ($i = count($tempPath2); $i < count($tempPath1); $i++)
        array_pop ($tempPath3);
    
    $urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);
    
    if ($urladdr{strlen($urladdr) - 1}== '/')
        define('URLADDR', 'http://' . $urladdr);
    else
        define('URLADDR', 'http://' . $urladdr . '/');
    
    unset($tempPath1, $tempPath2, $tempPath3, $urladdr);
    

    上面的代码定义了两个常量。 ABSPATH 包含应用程序根目录(本地文件系统)的绝对路径,而 URLADDR 包含应用程序的完全限定 URL。它确实适用于 mod_rewrite 情况。

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2013-05-13
      • 2022-12-02
      • 1970-01-01
      • 2014-05-31
      • 2010-09-16
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多