Skip to content

Instantly share code, notes, and snippets.

@rochellelewis
Last active November 24, 2015 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rochellelewis/800828d8d9e49179f50e to your computer and use it in GitHub Desktop.
Save rochellelewis/800828d8d9e49179f50e to your computer and use it in GitHub Desktop.
PHP Relative Pathing
<?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);
?>
<!-- HEAD-UTILS HTML GOES DOWN HERE -->
<?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");
?>
<!-- HTML/PAGE CONTENT GOES HERE -->
<?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__;
@rochellelewis
Copy link
Author

The above code will create a variable $PREFIX which can be used to automatically resolve the correct directory path when linking assets within your templated projects. For example, use this when loading internal CSS files in your head-utils.php file.

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

INSTRUCTIONS

  1. Add root-path.php to the root of your project.
  2. Add the code inside of head-utils.php (lines 1-14), to your HTML head-utils file at the very top.
  3. Add the code inside of index.php (lines 1-9), to the top of EACH of your pages.
  4. Use the $PREFIX variable when linking to an internal asset in your head-utils.php file. See examples below.

EXAMPLES

Echo the $PREFIX variable when linking/loading internal assets inside a templated-out portion of your layout:

Inside of your head-utils.php:
<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:

Echo the $PAGE_TITLE inside head-utils.php:
<title><?php echo $PAGE_TITLE; ?></title>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment