代码之家  ›  专栏  ›  技术社区  ›  ParoX

如何从URL获取当前的web目录?

  •  0
  • ParoX  · 技术社区  · 15 年前

    http://www.example.com/sites/dir/index.html

    我正在尝试使用:

     $URL = $_SERVER["REQUEST_URI"];
     preg_match("%^/(.*)/%", $URL, $matches);
    

    抱歉,我知道dirname…它给出了完整的目录路径。我只想要第一个目录。。。。所以如果是www.example.com/1/2/3/4/5/index.html 然后它只返回1,而不是/1/2/3/4/5/

    5 回复  |  直到 12 年前
        1
  •  2
  •   Sarfraz    15 年前

    使用 dirname 功能如下:

    $dir =  dirname($_SERVER['PHP_SELF']);
    $dirs = explode('/', $dir);
    echo $dirs[0]; // get first dir
    
        2
  •  1
  •   Gumbo    15 年前

    使用 parse_url $_SERVER['REQUEST_URI'] 然后你就可以用 explode :

    $_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $segments = explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1));
    
    echo $segments[1];
    
        3
  •  1
  •   Levi Hackwith    15 年前

    dirname函数应该可以满足您的需要

    http://us3.php.net/manual/en/function.dirname.php

    <?php
        $URL = dirname($_SERVER["REQUEST_URI"]);
    ?>
    
        4
  •  0
  •   sebilasse    12 年前

    只是想另外推荐检查前缀“/”或“\”

    $testPath = dirname(__FILE__);
    $_testPath = (substr($testPath,0,1)==DIRECTORY_SEPARATOR) ? substr($testPath,1):$testPath;
    $firstDirectory = reset( explode(DIRECTORY_SEPARATOR, dirname($_testPath)) );
    echo $firstDirectory;
    
        5
  •  0
  •   solarbaypilot    8 年前

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

    如果您担心目录分隔符,还可以执行以下操作:

    $currentWebDir = str_replace('\\', '/', substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT'])));
    

    还要注意francecomm提到的mod\u重写问题