I have been learning syntax for PHP and practicing it. I come from a .NET background so masterpages always made things pretty easy for me when it came to headers and footer
I know this is very late, just wanted to add my "pennies worth" to this question.
My suggestion would be to create methods for this, e.g my root is: var/www/htdocs/ and the functions file is in includes/functions/template-parts.php.
My functions would look as such:
<?php
define("DOC_ROOT", "/var/www/htdocs/"); # Add a trailing slash to make it a little easier
function GetHeader()
{
return include DOC_ROOT . 'includes/parts/header.htm'; # Header found at include/parts/header.htm
}
function GetFooter()
{
return include DOC_ROOT . 'includes/parts/footer.htm'; # Footer found at include/parts/footer.htm
}
?>
And used as such:
<?php
# From the main page (/var/www/htdocs/index.php)
require_once 'includes/functions/template-parts.php';
GetHeader();
?>
<!-- Page content -->
<?php
GetFooter();
?>
For small sites, include/include_once and require/require_once are great, I haven't built a site without them in years. I would, however, recommend making sure each of your include files is a discrete code block that is valid XML. What I mean is don't open a tag in one include and close it in another, or vice versa - it will make changes complex and more prone to break things because you have dependencies between files. Happy coding!
This is a perfectly fine method, as long as your site doesn't outgrow the 20 pages threshold. I'd however advise to use include() in function style, not as construct, and place these templates in a separate subfolder. If there is no PHP code in them, also use a .htm file extension (htm designating partial html).
include("template/main/header.htm"); // would still parse PHP code!
The disadvantage with this approach is, that you somewhen end up injecting HTML through global variables into it. $HEAD='<link...>'; include("../header.htm")
. Which is not bad per se, but can quickly amass cruft.
You can also do it the other way round. Have a main page with header/footer and include only the body.
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<?php include $page ?>
</body>
</html>