Relative Path using PHP

The following method will ensure that all of our LOCAL linked resources in our head-utils.php file will load properly on every page of our site. This code will create a variable $PREFIX which will be used to automatically resolve the correct directory path sitewide. For example, you will use this method when loading internal CSS files in your head-utils.php file.

This does not apply to assets you would load using require_once().

Instructions

Review the source code in the panels below.

  1. Add the file root-path.php to the active root of your project. (This should either be the true project root, or /public_html)
  2. Add the code inside of head-utils.php to the very top of your head-utils.php file.
  3. Add the code inside of index.php to the top of EACH web page.
  4. Use the $PREFIX variable when linking to an internal asset, such as a CSS file, in your head-utils.php file. See examples below.

root-path.php

<?php
/**
 * defines the root path of the entire site
 * @see https://raw.githubusercontent.com/kingscreations/farm-to-you/master/root-path.php FarmToYou Definition
 **/

$ROOT_PATH = __DIR__;

head-utils.php

<?php
/**
 * Get the relative path.
 * @see https://raw.githubusercontent.com/kingscreations/farm-to-you/master/php/lib/_header.php FarmToYou Header
 **/

// include the appropriate number of dirname() functions
// on line 8 to correctly resolve your directory's path
require_once(dirname(dirname(__DIR__)) . "/root-path.php");
$CURRENT_DEPTH = substr_count($CURRENT_DIR, "/");
$ROOT_DEPTH = substr_count($ROOT_PATH, "/");
$DEPTH_DIFFERENCE = $CURRENT_DEPTH - $ROOT_DEPTH;
$PREFIX = str_repeat("../", $DEPTH_DIFFERENCE);
?>

index.php

<?php
/*grab current directory*/
$CURRENT_DIR = __DIR__;
/*set page title here*/
$PAGE_TITLE = "MY PAGE TITLE";
/*load head-utils.php*/
require_once("lib/template/head-utils.php");
?>

Examples

Echo the $PREFIX variable when linking/loading internal assets in your head-utils.php file:

<link rel="stylesheet" href="<?php echo $PREFIX; ?>lib/css/styles.css" type="text/css" />

Ensure that each page can have it's own unique title text when using a head-utils.php file:

<title><?php echo $PAGE_TITLE; ?></title>