PHP Programming/headers and footers

From Wikibooks, open books for an open world
Jump to: navigation, search

Create the header and footer files:

Create a file called "header.php" and enter the html code that you'd like at the top of each page as follows:

<html>
<head>
    <title><?php echo $title; ?></title>
</head>
<body>

<h1>Our Web Site</h1>
<!-- end header -->

Create a file called "footer.php" and enter the html code that you'd like at the bottom of each page as follows:

<!-- begin footer -->
<p>Web Site last changed on 1/1/2005.</p>
</body>
</html>

Now we will create a web page that uses these headers and footers. Create a file called "page.html" and enter the following html code.

<?php
$title = "Welcome";                   // (1) Set the title
include "header.php";                 // (2) Include the header
?>

<!-- begin page content -->
<p><b>Welcome to our web site.</b></p>
<p style='text-align: center;'>
We're using PHP to provide you with dynamic content
for a better web experience.
</p>
<!-- end page content -->

<?php
include "footer.php";                 // (3) Include the footer
?>


We set the title for the page using (1)
We then include the header page using (2)
And we include the footer page using (3)

The final page should look like this:

<html>
<head>
    <title>Welcome</title>
</head>
<body>

<h1>Our Web Site</h1>
<!-- end header -->

<!-- begin page content -->
<p><b>Welcome to our web site.</b></p>
<p style='text-align: center;'>
We're using PHP to provide you with dynamic content
for a better web experience.
</p>
<!-- end page content -->

<!-- begin footer -->
<p>Web Site last changed on 1/1/2005.</p>
</body>
</html>

Files included in this way act as if their text was inserted into the main document right at the include() call. PHP then continues to process the inserted file, allowing the inserted file to access all previously defined variables and functions (so $title in header.php was replaced with the value set in page.html: "Welcome"). This can have unintended consequences if a file is included more than once. To learn how to correctly include files containing functions and classes, see PHP Include Files.


Return to PHP.