Search code examples
phpconfigurationincludeconfiguration-filesinclude-path

Including config file in PHP


I am developing a project where I am not able to include the files.

My Folder Structure:

--Myproject
-----Config
----------config.php
-----Includes
----------Images
---------------image.jpg
----------CSS
---------------test.css
----------JS
---------------test.js
-----Modules
----------Home
---------------index.php
----------Contact 
----------MyPage

enter image description here

I am trying to access the config file which is inside the Config/config.php in my Modules/Home/index.php

But I am not able to include the config file?

I tried:

1.
define("ROOT", __DIR__ ."/");

2.
define("HTTP", ($_SERVER["HTTP_HOST"] == "localhost")
   ? "http://localhost/myproject/"
   : "http://your_site_name.com/"
);
<img src="<?php print HTTP; ?>images/banner.gif">

3.
define('PROJECT_ROOT', getcwd());

4.
$_SERVER['DOCUMENT_ROOT'];

Ref: [link][2]

5.
echo $_SERVER['SERVER_NAME'];

How can I like a config.php which is out side the folder structure but inside my project?


Solution

  • You can either use absolute path which could be /Myproject/Config/config.php or reset your directory by navigating in upper level folder and then going to your require file ../../Config/config.php

    So you can manage to include with

    include('../../Config/config.php');
    

    As stated in include documentation

    If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

    Edited

    Let's analyze include path. We are actually in Modules/Home/ folder. te reach root level and can get inside Config folder we need to go two level upper, and we can do this by doing ../ for each level, so in our case ../../. Now that we are in root directory we can navigate through Config/ and get our desired file config.php. Now mixing all toghter will will have ../../Config/config.php.