phprequireheaddocument-body

Can PHP's require be used to require the head and body at the same time?


Is it possible to use PHP to include the contents of the <body> on one page, and add it to the <body> of the other page, while doing the same thing for the header? Or is it just easier / better to use two pages? This is kind of what I'm going for:

Some Page

<html>
<head>
 - nav.php's header -
 - stuff special to Some Page -
</head>
<body>
 - nav.php's body -
 - content special to Some Page -
</body>
</html>

I know the require statement can be used to take the whole contents of a file. Is there some sort of "merge" statement to kind of merge the pages together?


Solution

  • You are going to run into all sorts of security, re-use and maintenance issues if you rely on the inline behaviour of included files in PHP. But if you stick to some simple rules you can avoid these problems:

    So applying these to your base page above, and observing the established good practice of putting includes/requires at the top of your page....

    <?php
    // always start your page with a PHP block - it makes interfering with the headers
    // much less painful
    
    require_once('nav.inc.php');
    
    function local_head_content()
    {
      ...
    }
    
    function local_body_content()
    {
       ...
    }
    ?>
    <html>
    <head>
     <?php 
       nav_head_content();
       local_head_content(); 
     ?>
    </head>
    <body>
     <?php
       nav_body_content();
       local_body_content();
    </body>
    </html>
    

    But it would probably be better to invoke local_head_content() / local_body_content() as callbacks from nav content.

    (yes it is possible to do what you ask, even without function calls - but it would be a very bad idea which is why I've not explained how to do this).

    A more conventional approach to solving the problem of shared content across different files is to use a front controller pattern - instead of the webserver selecting the page specific content, this is done in the PHP code with all URLs pointing to the same entry script.