PHP URL Directory


PHP URL Directory

如果URL如下:

如果:http://www.imvu-e.com/products/dnr/
然后:http://www.imvu-e.com/products/dnr/

如果:http://www.imvu-e.com/products/dnr/?
然后:http://www.imvu-e.com/products/dnr/

如果:http://www.imvu-e.com/products/dnr/index.php
然后:http://www.imvu-e.com/products/dnr/

如果:http://www.imvu-e.com/products/dnr/page.php?var=2
然后:http://www.imvu-e.com/products/dnr/

如果:http://www.imvu-e.com/products/dnr
然后:http://www.imvu-e.com/products/

我该怎么做?

我的尝试:

print "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/";

看看parse_url()函数。

它会返回您需要的任何东西。

只需打印parse_url的结果(),就可以看到返回的结果。你可能想要这样的东西:

$ARRurlParts = parse_url($orgurl);
$newURL = $ARRelem["scheme"].
"://".$ARRelem["host"].
((isset($ARRelem["port"]))?":".$ARRelem["port"]:"").
$ARRelem["path"];

您的"尝试"的问题是$_SERVER['REQUEST_URI']将包含用户传递的所有内容,包括index.php和问号,甚至更多。为了得到你想要的东西,你需要解析$_SERVER['REQUEST_URI']:

  • 如果它以斜线/结尾,则保持原样
  • 否则,请找到字符串中的最后一个斜杠,并从开始到包括该斜杠的子字符串
  • 最后将结果附加到http://(或带有域名的https://)上

最终使用了这个

$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$address = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
$parseUrl = parse_url(trim($address));
$parent = (substr($parseUrl['path'], -1) == '/') ? $parseUrl['path'] : dirname($parseUrl['path']) . "/";
return $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['port'] . $parent;

在一定程度上受到Erwin Moller的回答(我为什么投票)和网络截图的启发。

您可以删除从最后一个反斜杠到字符串末尾的所有内容。我确信dirname($_SERVER['REQUEST_URI'])不会胜任这项工作。您也可以尝试使用dirname($_SERVER['SCRIPT_FILENAME'])。最后一个应该工作,如果你没有一些幻想。访问重写规则。