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

后端 未结 5 909
[愿得一人]
[愿得一人] 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: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

提交回复
热议问题