php 获取当前脚本的基目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3429262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:43:01  来源:igfitidea点击:

Get base directory of current script

php

提问by cdxf

This is the url of my script: localhost/do/index.php

这是我的脚本的网址: 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'

采纳答案by Calvin

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/do/

回答by www333

$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);

回答by Your Common Sense

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/

回答by icc97

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_SELFinstead of REQUEST_URIas dirname('/do/')gives '/'(or '\') in Windows, when you want '/do/'to be returned.

当我实现其中一些答案时,我遇到了一些问题,因为我使用的是 IIS,而且我还想要一个带有协议的完全限定 URL。当您想要返回时,我在 Windows 中使用PHP_SELF而不是REQUEST_URIas dirname('/do/')Give '/'(或'\') '/do/'

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
    $protocol = 'http://';
} else {
    $protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);

回答by mgutt

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.jpglocated in images/and you have the following code:

假设您已经image.jpg找到images/并拥有以下代码:

<img src="<?php echo $url; ?>../image.jpg" />

Now assume that $urlcould contain different values:

现在假设$url可以包含不同的值:

  • http://example.com/index.php
  • http://example.com/images/
  • http://example.com/images//
  • http://example.com/
  • etc.
  • http://example.com/index.php
  • http://example.com/images/
  • http://example.com/images//
  • http://example.com/
  • 等等。

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.) 文件和目录的不同结果

File
dirname('http://example.com/images/index.php')returns http://example.com/images

文件
dirname('http://example.com/images/index.php')返回http://example.com/images

Directory
dirname('http://example.com/images/')returns http://example.com

目录
dirname('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 removed
dirname('http://example.com//images//index.php')returns http://example.com//images

2.) 一些多斜线将被删除
dirname('http://example.com//images//index.php')返回http://example.com//images

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()只删除了一些多斜线,所以我开了一个错误票

3.) Root URL does not return root directory
dirname('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 path
dirname('foo/bar')returns .

4.) 根目录返回相对路径
dirname('foo/bar')返回.

I would expect /.

我会期待/

5.) Wrong encoded URLs
dirname('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

回答by kiamlaluno

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']);

回答by Med Abida

the best way is to use the explode/implode function (built-in PHP) like so

最好的方法是像这样使用explode/implode函数(内置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;

回答by hbw

dirnamewill 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”)。

回答by TylersSN

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"

回答by Ivan Castellanos

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;