Search code examples
phpreferencedirectorystructurerequire-once

Using PHP requires with varying directory levels


I have a project with the following directory structure (simplified):

+css
+js
+partials
  -header.php
  -footer.php
+blog
  -index.php
-index.php

I want to require_once the header.php and footer.php in both the blog index.php and the root index.php using the following the code:

<?php require_once("partials/header.php"); ?>

But of course in the blog it doesn't work because the header.php points to the css and js files relevant to the root index.php not the blog index.php.

Is there away to negate this or do I need two partials folders one at the root level and one at the blog level.


Solution

  • create a file called constants.php and include this at the top of your scripts. define this constant as your base path to the root directory of your files:

    define("BASE_PATH", "http://www.yourURL.com/");
    

    then to make sure the correct path is used simply prepend this constant to your urls:

    require_once(BASE_PATH."/any_subdirectory/anyfilename.php");