midgetgrimm midgetgrimm - 13 days ago 6
PHP Question

Include a file from one directory to another in the same level not working

Okay, so I am trying to include a header.php which is in my

WEBROOT/common/header.php


but if I try to include it on a file in
WEBROOT/legal/legal.php
it does not work.

I have tried the following

include 'common/header.php';
include '/common/header.php';
include './common/header.php';
include '../common/header.php';
include __DIR__ . 'common/header.php';
include 'http://siteurl.com/common/header.php';


The file structure seems basic enough

index.php
-/common/header.php
-/legal/legal.php

Answer

Create a config file with .php or .ini that can store DocumentRoot.


.php approach:

if (!defined('_BASE_DIR_')) {
    define('_BASE_DIR_', '/var/www/html/site');
}

Then use this constant in your code like so:

require_once 'constants.php';
require_once _BASE_DIR_.'/legal/legal.php';

.ini approach:

[common]
base_dir=/var/www/html/site

Read the .ini file like so:

$ini = parse_ini_file('config.ini', true);

Then include the files like so:

require_once $ini['common']['base_dir'].'/legal/legal.php';

A word of caution, the require or parse_ini_file that reads the constants may have the same path issues you are already encountering. The best solution is to use a single file to load all the pages, but that discussion would be outside the scope of your question.

Comments