php 获取基本路径/URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24008825/
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
Getting the base path/URL
提问by Raja
I am trying to get the base path of the documents through a function as I do not want to find the paths like ../folder1/folder2/mypage.php
or ../../../folder1/folder2/somepage.php
.
我正在尝试通过函数获取文档的基本路径,因为我不想找到类似../folder1/folder2/mypage.php
或的路径../../../folder1/folder2/somepage.php
。
Therefore I tried...
因此我尝试...
function getBaseUrl() {
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
return $protocol.$hostName.$pathInfo['dirname']."/";
}
Then i give write the code...
然后我给写代码...
$base = getBaseUrl();
require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';
Both the files qry.php
& functions.php
is in http://localhost/mysite/_include/db/
两个文件qry.php
&functions.php
都在http://localhost/mysite/_include/db/
While i run the page, error shows ...
当我运行页面时,错误显示...
Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\mysite\_include\header.php on line 9
Warning: require_once(http://localhost/mysite/_include/db/qry.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\mysite\_include\header.php on line 9
Fatal error: require_once(): Failed opening required 'http://localhost/mysite/_include/db/qry.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\mysite\_include\header.php on line 9
I tried by echoing the getBaseUrl() like echo $base;
and it is showing the right path i.e. http://localhost/mysite/
.
我尝试通过回显 getBaseUrl() 之类的方法echo $base;
,它显示了正确的路径,即http://localhost/mysite/
.
What should I do ?
我该怎么办 ?
回答by krozero
you can use $_SERVER['DOCUMENT_ROOT']
您可以使用 $_SERVER['DOCUMENT_ROOT']
回答by xdazz
You should just use the absolute path on the server instead of url.
您应该只使用服务器上的绝对路径而不是 url。
You could get the base path by using __DIR__
.
您可以使用__DIR__
.
For example:
例如:
// just example, change to fit your real path.
$base = __DIR__ . '/../';
require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';