How to do relative pathing? how to use __dir__
here is my file structure before
public_html
├── config
| |__config.php
├── core
| |__init.php
├── helper
| |__helper.php
├── libraries
| |__page1.php
├── templates
│ ├── page1template.php
│
│__index.php
│__page1.php
After having too many pages. I want to tiddy them up into "rep" folder and "admin" folder. so my new file structure look like this
public_html
├── config
| |__config.php
├── core
| |__init.php
├── helper
| |__helper.php
├── libraries
| |__page1.php
├── templates
│ ├── page1template.php
│
│__index.php
|
├── rep
| |__page1.php
├── admin
│ ├── page1.php
The problem is, my requires and includes are still absolute pathing. see a sample below
my init file
//Start Session
session_start();
//Include Configuration
require_once('config/config.php');
//Helper Function Files
require_once('helpers/system_helper.php');
require_once('helpers/format_helper.php');
//Autoload Classes
function __autoload($class_name){
require_once('libraries/'.$class_name .'.php');
}
my page1.php
<?php require('core/init.php'); ?>
//Get Template & Assign Vars
$template = new Template('templates/rep/page1.php');
if I add an "../" in front of every path. then the page will loads correctly. see below
require_once('../config/config.php');
require_once('../helpers/system_helper.php');
require_once('../helpers/format_helper.php');
require_once('../libraries/'.$class_name .'.php');
require('../core/init.php');
$template = new Template('../templates/rep/page1.php');
but then my index.php will break because index is in the root folder, so the new path is wrong relative to it. I found two question with related issue. I suspect it is related to using __dir__
to replace ../ but I dont know where to put it.
Are PHP include paths relative to the file or the calling code?
For me personally, I try to make includes relative to the file doing the including, if I'm sure the structure is supposed to be a certain way. For instance, you could make a file at core/loader.php right next to core/init.php ... Then if you assume the relative structure between the loader and the other files would always remain the same, core/loader.php could be something like
<?php
// Get the path of whatever folder is holding the core/config/etc folders
$main_dir=RealPath(DirName(__FILE__).'/../');
require("{$main_dir}/config/config.php");
require("{$main_dir}/helpers/system_helper.php");
// etc
?>
The point here being that you can now move that set of folders anywhere you want (recommendation: outside public_html), and they should still load, as long as you require'ed the right path to the loader.