How can I get the current web directory from the URL?

后端 未结 5 907
[愿得一人]
[愿得一人] 2021-01-28 03:09

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

相关标签:
5条回答
  • 2021-01-28 03:20

    Use the dirname function like this:

    $dir =  dirname($_SERVER['PHP_SELF']);
    $dirs = explode('/', $dir);
    echo $dirs[0]; // get first dir
    
    0 讨论(0)
  • 2021-01-28 03:21

    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;
    
    0 讨论(0)
  • 2021-01-28 03:27

    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

    0 讨论(0)
  • 2021-01-28 03:28

    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];
    
    0 讨论(0)
  • 2021-01-28 03:34

    The dirname function should get you what you need

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

    <?php
        $URL = dirname($_SERVER["REQUEST_URI"]);
    ?>
    
    0 讨论(0)
提交回复
热议问题