dongyu9850
dongyu9850
2010-07-15 20:43

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

已采纳

If I have a URL that is http://www.example.com/sites/dir/index.html, I would want to extract the word "sites". I know I have to use regular expressions but for some reason my knowledge of them is not working on PHP.

I am trying to use :

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

But I must be doing something wrong. I would also like it to have a catch function where if it is at the main site, www.example.com then it would do the word "MAIN"

Edit: sorry, I've known about dirname...It gives the full directory path. I only want the first directory.... So if its www.example.com/1/2/3/4/5/index.html then it returns just 1, not /1/2/3/4/5/

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • dragon071111 dragon071111 11年前

    Use the dirname function like this:

    $dir =  dirname($_SERVER['PHP_SELF']);
    $dirs = explode('/', $dir);
    echo $dirs[0]; // get first dir
    
    点赞 评论 复制链接分享
  • duancuisan2503 duancuisan2503 4年前

    A simple and robust way is:

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

    If you are worried about DIRECTORY_SEPARATORS, you could also do:

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

    Also be aware of mod_rewrite issues mentioned by FrancescoMM

    点赞 评论 复制链接分享
  • dongyi7901 dongyi7901 11年前

    Use parse_url to get the path from $_SERVER['REQUEST_URI'] and then you could get the path segments with explode:

    $_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $segments = explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1));
    
    echo $segments[1];
    
    点赞 评论 复制链接分享
  • dtr32787 dtr32787 11年前

    The dirname function should get you what you need

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

    <?php
        $URL = dirname($_SERVER["REQUEST_URI"]);
    ?>
    
    点赞 评论 复制链接分享
  • dongxiezhi0590 dongxiezhi0590 8年前

    Just wanted to recommend additionally to check for a prefixed "/" or "\" and to use DIRECTORY_SEPARATOR :

    $testPath = dirname(__FILE__);
    $_testPath = (substr($testPath,0,1)==DIRECTORY_SEPARATOR) ? substr($testPath,1):$testPath;
    $firstDirectory = reset( explode(DIRECTORY_SEPARATOR, dirname($_testPath)) );
    echo $firstDirectory;
    
    点赞 评论 复制链接分享

相关推荐