Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

php - How to get everything after the domain name into a string

My goal is to get everything after the domain name into a string. As in mysite.com/page/page2 would result in a string "page/page2". That I can do, however it starts giving me problems when, for example, the site is in a subfolder and not in root, then the folder the site is in will also be included in the string and if I'm not using mod_rewrite to get pretty links, it will also add index.php to the string.

So, I would need a trick or two to make the script understand whether or not the site is in a subfolder such as mysite.com/sitefolder/page/page2 and that it would still result in a string

page/page2

If the site doesn not use mod_rewrite and the url is mysite.com/sitefolder/index.php/page/page2, it would still result in a string

page/page2

Keep in mind that I have URL and USE_MOD_REWRITE defined in a config file, so no need for magic. I just have no idea how to go about getting that string. I know I could do $_SERVER['REQUEST_URI'] to get the string, but then index.php would still be in it. I'm sorry if I didn't explain well enough, but all help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • get the path by parsing the request uri
  • remove eventual script name from the end of the string (e.g. index.php)
  • rtrim any trailing slashes

    $request = parse_url($_SERVER['REQUEST_URI']);
    $path = $request["path"];
    $result = rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
    

EDIT

$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request["path"];

$result = trim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');

$result = explode('/', $result);
$max_level = 2;
while ($max_level < count($result)) {
    unset($result[0]);
}
$result = '/'.implode('/', $result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...