Search code examples
phphtml.htaccessinclude

.htaccess for header and footer using PHP


I know that I can write

php_value auto_prepend_file "/root-directory/header.php"
php_value auto_append_file "/root-directory/footer.php"

into .htaccess to include header and footer at the top and the end of every single page, but this would put them even before/after <html> and <body> tags.

It works anyway, but I know that it isn't a good way to set up an html page.

While I can "fix" the problem with the footer by putting </body> and </html> tags at the end of it (even if it isn't such a good thing having every single source code without closing tags), I can't find a way to fix the header.

Is there a way to tell .htaccess to put the header right after <body> tag and the footer right before </body>?


Solution

  • Instead of your header.php and footer.php files containing (what sounds like) raw HTML (or HTML with PHP embedded) you could perhaps assign this content to variables and use the variables inside your HTML page - wherever you want the content to appear. You could call this file template-variables.php and then you'd only need one file that you include with auto_prepend_file.

    For example:

    php_value auto_prepend_file "/root-directory/template-variables.php"
    

    Then in template-variables.php:

    <?php
    // Template variables...
    // (NB: Using HEREDOC <<< syntax)
    $HEADER= <<<EOF
    <header>
        <h1>Header goes here</h1>
        <p>More content goes here...</p>
    </header>
    EOF;
    
    $FOOTER= <<<EOF
    <footer>
        <p>Footer content goes here...</p>
        <p>Copyright etc.</p>
    </footer>
    EOF;
    

    In your HTML/PHP document:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <!-- PHP: Short echo format -->
        <?=$HEADER?>
    
        <p>Some more content goes here...</p>
    
        <?=$FOOTER?>
    </body>
    </html>
    

    To be a bit more encapsulated you could use an associative array to hold your template variables, then you only have one variable in the global namespace. For example:

    <?php
    // Template variables...
    $TEMPLATE_VARIABLES = [];
    $TEMPLATE_VARIABLES['HEADER'] = 'Hello world';
    :
    

    You can then easily traverse all your "template variables" in your script if needed.