I currently learning HTML, JS and PHP all at the same time (cus why not?)
And implementing the header.html in PHP is not so fun.
It works on the main page or "index.php" by just adding:
<?php include("header.html");?>ex.php
And then the other pages by adding:
<?php include("../header.html");?>ex.php
But after a while you forget how many "../../../" you need to put in, in order to get to root of the server folder. Is there a way to get to root of webserver easily? simply "/header.html" is not working out.
any ideas?
Solution?:
My current solution is simple to set the header path as
/home/yuannan/Web/header.html
Or where your file is from the ROOT OF THE SERVER and not the web server
What I usually do is:
Create a helper file "setpath.php" which is going to set the correct PHP path(s). In this file I work with relevant paths which are webroot independent:
function setPath() {
// get the path to the root folder of the
// project using our current known location
$bn = dirname(dirname(dirname(__FILE__)));
// Get absolute path
$bn=realpath($bn)."/";
// Extend with all needed paths (few examples)
$new_paths = $bn.PATH_SEPARATOR."$bn/db".PATH_SEPARATOR."$bn/templates";
// Set the environment
set_include_path(get_include_path() . PATH_SEPARATOR . $new_paths);
}
Now each file needs to know how to include this and call setPath()
, so from your index this is include("lib/php/setpath.php")
and from your lib/php/db this would be include("../setpath.php")
.
Additionally, I have found out that using Autoloading can save you lots of effort trying to figure out dependencies manually...
Finally, in some cases knowing the server webroot is needed. In these cases I use something like the following (also in my lib/php/ folder) which provides the file-system path and the webroot of the project as GLOBAL variables (... some may say bad practice ...)
// Fix document root to work with mod_alias (that maybe buggy)
$_SERVER['DOCUMENT_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['SCRIPT_FILENAME']);
// The root of the project in the Document
$SRV['BASEDIR'] = substr( __FILE__,0, strrpos(__FILE__, "/lib"));
$SRV['WEBROOT'] = substr( __FILE__,0, strrpos(__FILE__, "/lib"));
$SRV['WEBROOT'] = str_replace($_SERVER['DOCUMENT_ROOT'],"",$SRV['WEBROOT']);
I use the above tools along with some Autoloaders as the base of my projects. Hope that helps you or inspires someone to provide a better solution.
Andreas
What I have done for my website is simply set a general filepath and then use that throughout the website just below the <body>
tag. Pretty simple and straightforward. Just make sure your $Filepath
points to wherever you have your header file stored, it'll mitigate the issue of having to use backticks for each file layer. Like so:
<?php
{
$Filepath= "c:/wamp/www/";
include ("{$Filepath}header.php");
}
?>