Home > Software engineering >  How to include a file from "root"?
How to include a file from "root"?

Time:12-19

(This has amost certinaly been anwsered before, but I can't find it here...) I've been banging my head against the wall for far to long now, this should not be as complicated as I seem to find it...

File structure: .

./v1

./v2

./v2/index.php

./v2/Conn/dbopen.php

./v2/inc/functions/logit.php

./v2/inc/function/special_function/dosomething.php

I need to find some way of including "./v2/Conn/dbopen.php" from "where ever". If, in "logit.php", I enter: require "../../Conn/dbopen.php"; that won't work when I call logit() from logit.php in dosomething.php since then the path won't be right.

I'm not allowed to include it with the full URL (http*://www.example.com/v2/Conn/dbopen.php).

To make it a bit more complex (?), it needs to work for serveral server with different folder structure. http://localhost/site/, https://www.test.example.com/, https://www.example.com

I've tried with all sorts of solutions I can come up with. $_SERVER-variables, full URL-includes and all other ways I can think of.

CodePudding user response:

Assuming you are doing vanilla PHP:

$_SERVER['DOCUMENT_ROOT'];
// The document root directory under which the current script
// is executing, as defined in the server's configuration file. 

Use a boot file. Create a boot.php and include it at the top of every php file.

boot.php

<?php
// Put this in root dir of site
define('ROOT', __DIR__);
// make a convenience function
function root_path($path)
{
    return ROOT . $path;
}

Some other php

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . "/boot.php";
// Now we can write code that is more readable.
require_once root_path('/some/dir/file.php');

CodePudding user response:

@ryantxr:

Thanks, that should have worked, it looks like right way to go.

I've created the boot.php in the "root" of the site (/v2/boot.php) exatcly like you described above. I've created a test-file in /v2/test/testpath.php and at the top: require_once $_SERVER['DOCUMENT_ROOT'] . "/sitename/v2/boot.php"; It seem to work, when I step the code it don't fail.

But when I try require_once root_path('/Connections/opendb.php'); I get: "Fatal error: Uncaught Error: Call to undefined function root_path()' in C:\xampp\htdocs\sitename\v2\test\testpath.php:3" It looks good to me, but..

  •  Tags:  
  • php
  • Related