Skip to content

Instantly share code, notes, and snippets.

@AllenEllis
Last active February 15, 2019 19:39
Show Gist options
  • Save AllenEllis/fe8ee666b0868be66a1bb7144c19dfa2 to your computer and use it in GitHub Desktop.
Save AllenEllis/fe8ee666b0868be66a1bb7144c19dfa2 to your computer and use it in GitHub Desktop.
PHP: Introduction to include();

PHP: introduction to include();

For PHP code to execute, two things have to happen:

  1. The filename needs to end in .php
  2. The PHP code needs to exist between an opening PHP tag <?php and, optionally, a closing PHP tag ?>

Original code

Contents of index.html:

<html>
  <head>
    <!-- header content here -->
  </head>
  <body>
    <h1>Page name</h1>
    <p>Page content</p>
    <footer>
      <p>Contact info here</p>
    </footer>
  </body>
</html>

To seperate this out, we should consider which code we want to duplicate across every page, and move those over to separate files. We can make a new directory to hold those.

Before: directory structure
index.html
After: directory structure
index.php
templates/
 - header.php
 - footer.php

Revised code

The contents of index.php change to:

<?php
  include("templates/header.php");
?>
    <h1>Page name</h1>
    <p>Page content</p>

<?php
  include("templates/footer.php");
?>

New file: templates/header.php

<html>
  <head>
    <!-- header content here -->
  </head>
  <body>

New file: templates/footer.php

    <footer>
      <p>Contact info here</p>
    </footer>
  </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment