This is the url of my script: localhost/do/index.php
这是脚本的url: localhost/do/index.php。
I want a variable or a function that returns localhost/do
(something like $_SERVER['SERVER_NAME'].'/do'
)
我想要一个返回localhost/do的变量或函数(比如$_SERVER['SERVER_NAME'].'/do')
10 个解决方案
#1
28
Try:
试一试:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
print_r($parts);
EDIT:
编辑:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;
This should return localhost/do/
这应该返回localhost / /
#2
31
$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
#3
8
php has many functions for string parsing which can be done with simple one-line snippets
dirname() (which you asked for) and parse_url() (which you need) are among them
php有许多用于字符串解析的函数,可以使用简单的一行代码dirname()(您需要它)和parse_url()(您需要它)来完成
<?php
echo "Request uri is: ".$_SERVER['REQUEST_URI'];
echo "<br>";
$curdir = dirname($_SERVER['REQUEST_URI'])."/";
echo "Current dir is: ".$curdir;
echo "<br>";
address bar in browser is
地址栏在浏览器是
http://localhost/do/index.php
output is
输出是
Request uri is: /do/index.php
Current dir is: /do/
#4
8
I suggest not to use dirname()
. I had several issues with multiple slashes and unexpected results at all. That was the reason why I created currentdir():
我建议不要使用dirname()。我有几个问题,有多个斜杠和意想不到的结果。这就是我创建currentdir()的原因:
function currentdir($url) {
// note: anything without a scheme ("example.com", "example.com:80/", etc.) is a folder
// remove query (protection against "?url=http://example.com/")
if ($first_query = strpos($url, '?')) $url = substr($url, 0, $first_query);
// remove fragment (protection against "#http://example.com/")
if ($first_fragment = strpos($url, '#')) $url = substr($url, 0, $first_fragment);
// folder only
$last_slash = strrpos($url, '/');
if (!$last_slash) {
return '/';
}
// add ending slash to "http://example.com"
if (($first_colon = strpos($url, '://')) !== false && $first_colon + 2 == $last_slash) {
return $url . '/';
}
return substr($url, 0, $last_slash + 1);
}
Why you should not use dirname()
为什么不应该使用dirname()
Assume you have image.jpg
located in images/
and you have the following code:
假设您有image.jpg位于images/并且您有以下代码:
<img src="<?php echo $url; ?>../image.jpg" />
Now assume that $url
could contain different values:
现在假设$url可以包含不同的值:
http://example.com/index.php
- http://example.com/index.php
http://example.com/images/
- http://example.com/images/
http://example.com/images//
- http://example.com/images//
http://example.com/
- http://example.com/
- etc.
- 等。
Whatever it contains, we need the current directory to produce a working deeplink. You try dirname()
and face the following problems:
无论它包含什么,我们都需要当前目录来生成一个工作的深度链接。您尝试使用dirname()并面临以下问题:
1.) Different results for files and directories
1)。文件和目录的不同结果
Filedirname('http://example.com/images/index.php')
returns http://example.com/images
文件目录名(“http://example.com/images/index.php”)返回http://example.com/images
Directorydirname('http://example.com/images/')
returns http://example.com
目录,目录名(“http://example.com/images/”)返回http://example.com
But no problem. We could cover this by a trick:dirname('http://example.com/images/' . '&') . '/'
returns http://example.com/images/
但是没有问题。我们可以通过一个技巧来解决这个问题:dirname('http://example.com/images/')。“&”)。' / '返回http://example.com/images/
Now dirname()
returns in both cases the needed current directory. But we will have other problems:
现在,dirname()在这两种情况下都返回所需的当前目录。但我们还有其他问题:
2.) Some multiple slashes will be removeddirname('http://example.com//images//index.php')
returns http://example.com//images
2)。一些多个斜杠将被删除,返回http://example.com//images/index.php
Of course this URL is not well formed, but multiple slashes happen and we need to act like browsers as webmasters use them to verify their output. And maybe you wonder, but the first three images of the following example are all loaded.
当然,这个URL的格式不是很好,但是会出现多个斜杠,我们需要像浏览器一样使用它们来验证它们的输出。也许你想知道,下面这个例子的前三个图像都是加载的。
<img src="http://example.com/images//../image.jpg" />
<img src="http://example.com/images//image.jpg" />
<img src="http://example.com/images/image.jpg" />
<img src="http://example.com/images/../image.jpg" />
Thats the reason why you should keep multiple slashes. Because dirname()
removes only some multiple slashes I opened a bug ticket.
这就是为什么你应该保留多个斜杠的原因。因为dirname()只删除一些多次斜杠,所以我打开了一个bug罚单。
3.) Root URL does not return root directorydirname('http://example.com')
returns http:
dirname('http://example.com/')
returns http:
3)。根URL不返回根目录dirname('http://example.com')返回http: dirname('http://example.com/')返回http:
4.) Root directory returns relative pathdirname('foo/bar')
returns .
4)。根目录返回相对路径dirname('foo/bar')。
I would expect /
.
我希望/。
5.) Wrong encoded URLsdirname('foo/bar?url=http://example.com')
returns foo/bar?url=http:
5)。错误编码的url dirname('foo/bar?url=http://example.com')返回foo/bar?url=http:
All test results:
http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm#4329444
所有测试结果:http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm 4329444
#5
7
When I was implementing some of these answers I hit a few problems as I'm using IIS and I also wanted a fully qualified URL with the protocol as well. I used PHP_SELF
instead of REQUEST_URI
as dirname('/do/')
gives '/'
(or '\'
) in Windows, when you want '/do/'
to be returned.
当我实现其中一些答案时,我在使用IIS时遇到了一些问题,我还想要一个具有协议的完全限定URL。我使用PHP_SELF代替REQUEST_URI作为dirname('/do/')在Windows中给出'/'(或'\'),当您希望'/do/'返回时。
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
#6
2
If you want to include the server name, as I understood, then the following code snippets should do what you are asking for:
如我所理解的,如果您想要包含服务器名称,那么以下代码片段应该执行您所要求的操作:
$result = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
$result = $_SERVER['SERVER_NAME'] . __DIR__; // PHP 5.3
$result = $_SERVER['SERVER_NAME'] . '/' . dirname($_SERVER['REQUEST_URI']);
#7
1
dirname
will give you the directory portion of a file path. For example:
dirname将提供文件路径的目录部分。例如:
echo dirname('/path/to/file.txt'); // Outputs "/path/to"
Getting the URL of the current script is a little trickier, but $_SERVER['REQUEST_URI']
will return you the portion after the domain name (i.e. it would give you "/do/index.php").
获取当前脚本的URL有点麻烦,但是$_SERVER['REQUEST_URI']将返回您在域名之后的部分(也就是说,它将给您"/do/index.php")。
#8
1
the best way is to use the explode/implode function (built-in PHP) like so
最好的方法是像这样使用爆炸/内爆函数(内置PHP)
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parts = explode('/',$actual_link);
$parts[count($parts) - 1] = "";
$actual_link = implode('/',$parts);
echo $actual_link;
#9
0
My Suggestion:
我的建议:
const DELIMITER_URL = '/';
$urlTop = explode(DELIMITER_URL, trim(input_filter(INPUT_SERVER,'REQUEST_URI'), DELIMITER_URL))[0]
Test:
测试:
const DELIMITER_URL = '/';
$testURL = "/top-dir";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/this.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
Test Output:
测试输出:
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
#10
0
A shorter (and correct) solution that keeps trailing slash:
一个更短的(并且正确的)解决方案,持续使用斜线:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url_dir = preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $url);
echo $url_dir;
#1
28
Try:
试一试:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
print_r($parts);
EDIT:
编辑:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;
This should return localhost/do/
这应该返回localhost / /
#2
31
$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
#3
8
php has many functions for string parsing which can be done with simple one-line snippets
dirname() (which you asked for) and parse_url() (which you need) are among them
php有许多用于字符串解析的函数,可以使用简单的一行代码dirname()(您需要它)和parse_url()(您需要它)来完成
<?php
echo "Request uri is: ".$_SERVER['REQUEST_URI'];
echo "<br>";
$curdir = dirname($_SERVER['REQUEST_URI'])."/";
echo "Current dir is: ".$curdir;
echo "<br>";
address bar in browser is
地址栏在浏览器是
http://localhost/do/index.php
output is
输出是
Request uri is: /do/index.php
Current dir is: /do/
#4
8
I suggest not to use dirname()
. I had several issues with multiple slashes and unexpected results at all. That was the reason why I created currentdir():
我建议不要使用dirname()。我有几个问题,有多个斜杠和意想不到的结果。这就是我创建currentdir()的原因:
function currentdir($url) {
// note: anything without a scheme ("example.com", "example.com:80/", etc.) is a folder
// remove query (protection against "?url=http://example.com/")
if ($first_query = strpos($url, '?')) $url = substr($url, 0, $first_query);
// remove fragment (protection against "#http://example.com/")
if ($first_fragment = strpos($url, '#')) $url = substr($url, 0, $first_fragment);
// folder only
$last_slash = strrpos($url, '/');
if (!$last_slash) {
return '/';
}
// add ending slash to "http://example.com"
if (($first_colon = strpos($url, '://')) !== false && $first_colon + 2 == $last_slash) {
return $url . '/';
}
return substr($url, 0, $last_slash + 1);
}
Why you should not use dirname()
为什么不应该使用dirname()
Assume you have image.jpg
located in images/
and you have the following code:
假设您有image.jpg位于images/并且您有以下代码:
<img src="<?php echo $url; ?>../image.jpg" />
Now assume that $url
could contain different values:
现在假设$url可以包含不同的值:
http://example.com/index.php
- http://example.com/index.php
http://example.com/images/
- http://example.com/images/
http://example.com/images//
- http://example.com/images//
http://example.com/
- http://example.com/
- etc.
- 等。
Whatever it contains, we need the current directory to produce a working deeplink. You try dirname()
and face the following problems:
无论它包含什么,我们都需要当前目录来生成一个工作的深度链接。您尝试使用dirname()并面临以下问题:
1.) Different results for files and directories
1)。文件和目录的不同结果
Filedirname('http://example.com/images/index.php')
returns http://example.com/images
文件目录名(“http://example.com/images/index.php”)返回http://example.com/images
Directorydirname('http://example.com/images/')
returns http://example.com
目录,目录名(“http://example.com/images/”)返回http://example.com
But no problem. We could cover this by a trick:dirname('http://example.com/images/' . '&') . '/'
returns http://example.com/images/
但是没有问题。我们可以通过一个技巧来解决这个问题:dirname('http://example.com/images/')。“&”)。' / '返回http://example.com/images/
Now dirname()
returns in both cases the needed current directory. But we will have other problems:
现在,dirname()在这两种情况下都返回所需的当前目录。但我们还有其他问题:
2.) Some multiple slashes will be removeddirname('http://example.com//images//index.php')
returns http://example.com//images
2)。一些多个斜杠将被删除,返回http://example.com//images/index.php
Of course this URL is not well formed, but multiple slashes happen and we need to act like browsers as webmasters use them to verify their output. And maybe you wonder, but the first three images of the following example are all loaded.
当然,这个URL的格式不是很好,但是会出现多个斜杠,我们需要像浏览器一样使用它们来验证它们的输出。也许你想知道,下面这个例子的前三个图像都是加载的。
<img src="http://example.com/images//../image.jpg" />
<img src="http://example.com/images//image.jpg" />
<img src="http://example.com/images/image.jpg" />
<img src="http://example.com/images/../image.jpg" />
Thats the reason why you should keep multiple slashes. Because dirname()
removes only some multiple slashes I opened a bug ticket.
这就是为什么你应该保留多个斜杠的原因。因为dirname()只删除一些多次斜杠,所以我打开了一个bug罚单。
3.) Root URL does not return root directorydirname('http://example.com')
returns http:
dirname('http://example.com/')
returns http:
3)。根URL不返回根目录dirname('http://example.com')返回http: dirname('http://example.com/')返回http:
4.) Root directory returns relative pathdirname('foo/bar')
returns .
4)。根目录返回相对路径dirname('foo/bar')。
I would expect /
.
我希望/。
5.) Wrong encoded URLsdirname('foo/bar?url=http://example.com')
returns foo/bar?url=http:
5)。错误编码的url dirname('foo/bar?url=http://example.com')返回foo/bar?url=http:
All test results:
http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm#4329444
所有测试结果:http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm 4329444
#5
7
When I was implementing some of these answers I hit a few problems as I'm using IIS and I also wanted a fully qualified URL with the protocol as well. I used PHP_SELF
instead of REQUEST_URI
as dirname('/do/')
gives '/'
(or '\'
) in Windows, when you want '/do/'
to be returned.
当我实现其中一些答案时,我在使用IIS时遇到了一些问题,我还想要一个具有协议的完全限定URL。我使用PHP_SELF代替REQUEST_URI作为dirname('/do/')在Windows中给出'/'(或'\'),当您希望'/do/'返回时。
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
#6
2
If you want to include the server name, as I understood, then the following code snippets should do what you are asking for:
如我所理解的,如果您想要包含服务器名称,那么以下代码片段应该执行您所要求的操作:
$result = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
$result = $_SERVER['SERVER_NAME'] . __DIR__; // PHP 5.3
$result = $_SERVER['SERVER_NAME'] . '/' . dirname($_SERVER['REQUEST_URI']);
#7
1
dirname
will give you the directory portion of a file path. For example:
dirname将提供文件路径的目录部分。例如:
echo dirname('/path/to/file.txt'); // Outputs "/path/to"
Getting the URL of the current script is a little trickier, but $_SERVER['REQUEST_URI']
will return you the portion after the domain name (i.e. it would give you "/do/index.php").
获取当前脚本的URL有点麻烦,但是$_SERVER['REQUEST_URI']将返回您在域名之后的部分(也就是说,它将给您"/do/index.php")。
#8
1
the best way is to use the explode/implode function (built-in PHP) like so
最好的方法是像这样使用爆炸/内爆函数(内置PHP)
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parts = explode('/',$actual_link);
$parts[count($parts) - 1] = "";
$actual_link = implode('/',$parts);
echo $actual_link;
#9
0
My Suggestion:
我的建议:
const DELIMITER_URL = '/';
$urlTop = explode(DELIMITER_URL, trim(input_filter(INPUT_SERVER,'REQUEST_URI'), DELIMITER_URL))[0]
Test:
测试:
const DELIMITER_URL = '/';
$testURL = "/top-dir";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/this.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
Test Output:
测试输出:
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
#10
0
A shorter (and correct) solution that keeps trailing slash:
一个更短的(并且正确的)解决方案,持续使用斜线:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url_dir = preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $url);
echo $url_dir;