How to use PHP includes

PHP includes are fantastic because they save so much time which would otherwise be spent re-typing or copying and pasting the same code on each page.

For example, most websites have a header and footer repeated on every page, so by creating a header.php file and footer.php file, you're able to just include these files on each of your PHP pages.

Another advantage is that if you have an update to your header or footer, you then only have to change the relevant file, as opposed to updating every single page on your site.

How to use PHP includes | coding-tips.com.

You can basically use this to include anything you want, such as a gallery, slideshow, widget, etc - you don't have to use it for only headers and footers.

There are two options, 'include' and 'include_once'.

The difference between the two is exactly as it sounds, 'include' will display the same file as many times as it's inluded, while 'include_once' will only display the same file once, no matter how many times the file is included.

For the below example, we have our index.php file saved in our root folder.
In our root folder we have created a folder for our includes and have aptly named it 'includes'.
We have also created a header.php file and a footer.php file and saved both files in our 'includes' folder.

Be sure to always use the relative path (eg. includes/header.php) and not the absolute path (eg. https://mywebsite.com/includes/header.php).

includes/header.php:

<header>
<!-- Header content goes here -->
</header>

includes/footer.php:

index.php:

<html>
<head>
<!-- Title, meta data, CSS go here -->
</head>
<body>

<?php include_once('includes/header.php'); ?>

<!-- The rest of your content can go here, as well as other includes -->

<?php include_once('includes/footer.php'); ?>

</body>
</html>