My file structure:
/holiday/admin/list.php
/holiday/includes/functions.php # common functions
/holiday/index.php
# / is the document root
# /holiday/ is a "self-contained" sub-directory
# There are other "self-contained" sub-directories e.g. /promotion/, /international/
In functions.php I have a common function to generate the <head> part of an HTML; also, a function to return an absolute path from the document root. Note my attempt to calculate /holiday/includes/.
<? function get_path() {
// Technically, this returns dirname(__FILE__) - $_SERVER['DOCUMENT_ROOT']
return str_replace($_SERVER['DOCUMENT_ROOT'], "", dirname(__FILE__));
} ?>
<? function open_page($head = "", $body_id = "") { ?>
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="<? echo get_path() . "/../css/savvyextras.css"; ?>" />
<script type="text/javascript" src="<? echo get_path() . "/../scripts/modernizr.js"; ?>"></script>
...
<? } ?>
functions.php is included this way:
// From list.php
require_once('../includes/functions.php');
open_page(...);
// From index.php
require_once('./includes/functions.php');
open_page(...);
I feel like there must be a more straightforward approach to accomplish the same thing here. Any built-in PHP function for my get_path()? Maybe I should approach my problem differently?
Note:
Some folks suggested using a framework (which is a good thing). But, to help me (and others) understand this whole include-file thing, other non-framework explanations?
Related Discussions:
After experimenting more with this and gathering other inputs, I find using constant will do the trick:
So, if you need to move
/holiday/to a different sub-directory e.g./vacation/, you’d simply need to change one constant i.e.PREFIX.