获取基本路径/ URL

Raj*_*Raj 4 php url base-path

我试图通过函数获取文档的基本路径,因为我不想找到像../folder1/folder2/mypage.php或的路径../../../folder1/folder2/somepage.php.

所以我试过......

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']."/";
}
Run Code Online (Sandbox Code Playgroud)

然后我给写代码......

$base = getBaseUrl();
require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';
Run Code Online (Sandbox Code Playgroud)

这两个文件qry.phpfunctions.phphttp://localhost/mysite/_include/db/

当我运行页面时,错误显示...

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
Run Code Online (Sandbox Code Playgroud)

我尝试通过回显getBaseUrl()echo $base;,它显示正确的路径,即http://localhost/mysite/.

我该怎么办 ?

kro*_*ero 10

您可以使用 $_SERVER['DOCUMENT_ROOT']

  • 这在不同的服务器上不一致,因为它来自服务器的配置文件。 (2认同)

xda*_*azz 9

您应该只使用服务器上的绝对路径而不是url.

您可以使用获取基本路径__DIR__.

例如:

// just example, change to fit your real path.
$base = __DIR__ . '/../';

require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';
Run Code Online (Sandbox Code Playgroud)