7

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.

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/

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

What should I do ?

Raja
  • 772
  • 1
  • 15
  • 38

2 Answers2

15

you can use $_SERVER['DOCUMENT_ROOT']

krozero
  • 5,929
  • 3
  • 21
  • 33
  • 3
    This is not consistent across different server as it's coming from server's configuration file. – kta Feb 01 '17 at 05:11
12

You should just use the absolute path on the server instead of url.

You could get the base path by using __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';
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • If the file is in `_include/db/folder1/` then what should be the `$base` ? – Raja Jun 03 '14 at 07:07
  • I have tried your instruction. I am getting the path like `C:\xampp\htdocs\mysite\_include/../` and my site is opening perfectly. Will it work in my web hosting ? – Raja Jun 03 '14 at 07:12