简体   繁体   中英

How to include config file in multiple directories php pages

I have a following directory structure for my project in which I have Init.php file under core folder. I wanted to include this file on every pages under the views folder to auto load all my classes defined under classes folder. But when I am including require_once '../../core/Init.php'; from a sub-directory of views folder it gives me following error

require_once(classes/Config.php): failed to open stream: No such file or directory in

Including this file in every pages under the views folder

require_once 'core/Init.php';

core/Init.php

spl_autoload_register(function($class) {    
    require_once 'classes/' . $class . '.php';
});

My directory structure is as below

目录结构

I would like to include this single file ( core/Init.php ) into all my files, directories and sub-directories of views folder. Any one have an idea how would I do it.

Thanks!

The root of your problem is that your code actually gets executed from multiple directories.

Instead it should be called through a single point of entry (usually referred to as "bootstrap file").

Basically, you do something like this.

$config = require __DIR__ '/../config.php';
$page = $_GET['page'] ?? 'home';

if (in_array($page, $whitelist)) {
    require __DIR__ . "/path/to/pages/{$page}.php";
}

Oh, and don't refer to your template as "views". They are not.

Structure! When starting the application tell it where to find things then add the spl_autoload_register function and setup the things which are always accessible:

.../www/index.php
eg (in index.php):
chdir(__DIR__):

Now every thing starts at .../www/ directory. From that point you can start to setup all paths you wish to include. Relative or absolute.

Kind regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM